Java Reference
In-Depth Information
final class Foo {
private final AtomicIntegerArray atomicArray =
new AtomicIntegerArray(20);
public int getFirst() {
return atomicArray.get(0);
}
public void setFirst(int n) {
atomicArray.set(0, 10);
}
// ...
}
AtomicIntegerArray
guarantees a happens-before relationship between a thread that
calls
atomicArray.set()
and a thread that subsequently calls
atomicArray.get()
.
Compliant Solution (Synchronization)
To ensure visibility, accessor methods must synchronize access while performing opera-
tions on nonvolatile elements of an array, whether the array is referred to by a volatile or
a nonvolatile reference. Note that the code is thread-safe, even though the array reference
is not volatile.
final class Foo {
private int[] arr = new int[20];
public synchronized int getFirst() {
return arr[0];
}
public synchronized void setFirst(int n) {
arr[0] = n;
}
}
Synchronization establishes a happens-before relationship between threads that syn-
chronize on the same lock. In this case, the thread that calls
setFirst()
and the thread
that subsequently calls
getFirst()
on the same object instance both synchronize on that
instance, so safe publication is guaranteed.