Sunday, February 5, 2012

AtomicReference

On the previous article, I've talked about AtomicInteger and AtomicLong.
Now I'm going to show you another Atomic object that can ben used independently of the type of the object, taking advantage of Java Generics: AtomicReference.
AtomicReference is also used for an object that may be updated atomically, but this time the object is generic.

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.