Saturday, 21 January 2012

java.util.concurrent.atomic package


Classes from java.util.concurrent.atomic package allow us to use single variables concurrently without blocking access to them. The typical usage example is increasing the counter that is modified by many threads.

Instead of using the synchronized block, that blocks the access to the counter:
private long counter = 0;
private final Object mutex = new Object();
public void incrementCounter() {
synchronized (mutex) {
counter++;
}
}

or the synchronized method equivalent to the block with 'synchronized(this)':
public synchronized void incrementCounter() {
counter++;
}

you can use AtomicLong class, that guarantees non-blocking access:
private AtomicLong counter = new AtomicLong();
public void incrementCounter() {
counter.incrementAndGet();
}

Method incrementAndGet() besides incrementing counter's value, returns it.

Another typical usage is providing non-blocking access to an object, that is shared by many threads. Instead of synchronizing getter/setters methods:
private Object resource = new Object();
public synchronized Object getResource() {
return resource;
}
public synchronized void setResource(Object resource) {
this.resource = resource;
}

you can use AtomicReference class:





No comments:

Post a Comment