Working with the AtoMiC ToolKit

The java.util.concurrent.atomic package is a collection of 12 subclasses that support operations on single variables that are thread-safe and lock-free. In this context, thread-safe refers to code that accesses or mutates a shared single variable without impeding on other threads executing on the variable at the same time. This superclass was introduced in Java 7.

Here is a list of the 12 subclasses in the AtoMiC ToolKit. The class names, as you would expect, are self-descriptive:

  • java.util.concurrent.atomic.AtomicBoolean
  • java.util.concurrent.atomic.AtomicInteger
  • java.util.concurrent.atomic.AtomicIntegerArray
  • java.util.concurrent.atomic.AtomicIntegerFieldUpdater<T>
  • java.util.concurrent.atomic.AtomicLong
  • java.util.concurrent.atomic.AtomicLongArray
  • java.util.concurrent.atomic.AtomicLongFieldUpdater<T>
  • java.util.concurrent.atomic.AtomicMarkableReference<V>
  • java.util.concurrent.atomic.AtomicReference<V>
  • java.util.concurrent.atomic.AtomicReferenceArray<E>
  • java.util.concurrent.atomic.AtomicReferenceFieldUpdater<T,V>
  • java.util.concurrent.atomic.AtomicStampedReference<V>

The key to using the AtoMIC ToolKit is having an understanding of volatile variables. Volatile variables, fields, and array elements can be asynchronously modified by concurrent threads.

In Java, the volatile keyword is used to inform the javac utility to read the value, field, or array element from the main memory and not to cache them.

Here is a code snippet that demonstrates the use of the volatile keyword for an instance variable:

public class Sample {
private static volatile Sample myVolatileVariable; // a volatile
//
instance
//variable

// getter method
public static Sample getVariable() {
if (myVolatileVariable != null) {
return myVolatileVariable;
}

// this section executes if myVolatileVariable == null
synchronized(Sample.class) {
if (myVolatileVariable == null) {
myVolatileVariable = new Sample();
}
}
return null;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset