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:

or the synchronized method equivalent to the block with 'synchronized(this)':

you can use AtomicLong class, that guarantees non-blocking access:

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:

you can use AtomicReference class:

No comments:

Post a Comment