Friday, February 3, 2012

AtomicInteger and AtomicLong

The most common usage for the AtomicInteger is for counters.
Before Java 5, counters had to be implemented by the usage of synchronized blocks, or methods, with volatile declaration for the counter (for multiprocessor good behavioring code).
The AtomicInteger is a Java 5 replacement for these two methods that must be used combined together in order to avoid race conditions and to have correct value propagation to memory, to make it available for all multiprocessor threads, joining the best of these two worlds.

Usage of the AtomicInteger as a counter:


public class Counter {
  private AtomicInteger count = new AtomicInteger(0);
  public void incrementCount() {
    count.incrementAndGet();
  }
  public int getCount() {
    return count.get();
  }
}


By the usage of the incrementAndGet, the operations read, increment and set of the value into memory are treated as an atomic operation, that cannot be interrupted by another thread.

The AtomicLong behaves exactly like the AtomicInteger, but for long values.

No comments:

Post a Comment