
上QQ阅读APP看书,第一时间看更新
Working with the AtoMiC Toolkit
The java.util.concurrent.atomic package is a collection of 12 sub-classes 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 sub-classes in the AtoMiC Toolkit. The class names, as you would expect, are self-descriptive:
Atomic subclass |
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> |
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
public static Sample getVariable() // getter method
{
if (myVolatileVariable != null)
{
return myVolatileVariable;
}
// this section executes if myVolatileVariable == null
synchronized(Sample.class)
{
if (myVolatileVariable == null)
{
myVolatileVariable = new Sample();
}
}
}