Video in progress
How do the plain, opaque, acquire/release and volatile access modes in VarHandle differ, and when do you need them?
They form a ladder of guarantee strength: plain gives no ordering, opaque gives coherence for a single variable, acquire/release gives pairwise happens-before, and volatile gives one common order for everything. The weaker the mode, the cheaper it is, and the easier it is to get wrong.
📖 Answer
Since Java 9, VarHandle has replaced sun.misc.Unsafe and Atomic*FieldUpdater. It provides operations of different strength on a single field or array element:
| Mode | Methods | What it guarantees |
|---|---|---|
| plain | get/set |
like a regular field, nothing |
| opaque | getOpaque/setOpaque |
atomic, not cached, ordering for a single variable |
| release/acquire | setRelease/getAcquire |
writes before the release are visible to a reader that does the acquire |
| volatile | getVolatile/setVolatile |
one global order for all volatile operations |
The classic use is a single-producer queue:
class SpscSlot<T> {
private static final VarHandle READY;
static {
try {
READY = MethodHandles.lookup().findVarHandle(SpscSlot.class, "ready", boolean.class);
} catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
}
private T value;
private boolean ready;
void publish(T v) {
value = v; // plain write
READY.setRelease(this, true); // "publishes" everything before it
}
T poll() {
if ((boolean) READY.getAcquire(this)) return value; // value is visible
return null;
}
}
The difference between release/acquire and volatile is that it doesn't need a StoreLoad barrier. On x86 a volatile write produces a lock-prefixed instruction or mfence, while a release write is a plain mov. On ARM there's a difference too. On a very hot path this is noticeable.
Opaque is rarely needed: for example, a progress counter, where another thread should see the new value "at some point" but no other data is tied to it.
My position: you need none of this in business code. volatile, Atomic* and java.util.concurrent are enough. The weak VarHandle modes are for library-level work, when the gain is proven with JMH and there's a jcstress test. Otherwise you get bugs that take months to find.
Sign up to mark studied questions and save your progress.