Working with VarHandle API
1. Creating VarHandles (lookup)
| Factory | For |
|---|---|
findVarHandle(cls, name, type) | Instance field |
findStaticVarHandle(cls, name, type) | Static field |
arrayElementVarHandle(arrayClass) | Array element |
byteArrayViewVarHandle(viewClass, order) | byte[] as int/long view |
2. Using Atomic Operations
| Method | Effect |
|---|---|
compareAndSet(target, expected, new) | Volatile CAS |
getAndSet(target, new) | Atomic exchange |
getAndAdd(target, delta) | Atomic add (numeric) |
getAndBitwiseOr/And/Xor | Atomic bitwise |
3. Using Memory Ordering
| Mode | Semantics |
|---|---|
| Plain | No ordering, no atomicity guarantee |
| Opaque | Per-variable ordering, no synchronization |
| Acquire/Release | Pairwise happens-before |
| Volatile | Sequentially consistent (full fence) |
4. Accessing Array Elements Atomically
| API | Use |
|---|---|
VarHandle vh = arrayElementVarHandle(int[].class) | Setup |
vh.compareAndSet(arr, idx, exp, new) | CAS slot |
vh.getVolatile(arr, idx) | Volatile read |
5. Accessing Field Values
| Operation | Method |
|---|---|
| Read | get(target) |
| Write | set(target, val) |
| Volatile read/write | getVolatile / setVolatile |
| Acquire/Release | getAcquire / setRelease |
6. Understanding Performance Benefits vs Atomic Classes
| Aspect | VarHandle | AtomicX |
|---|---|---|
| Memory | Operates on existing field | Wrapper object overhead |
| Indirection | None | Object reference |
| Flexibility | Multiple ordering modes | Volatile only |
| Use | Fields in your own classes | Standalone counters |
7. Using Fence Operations
| Fence | Effect |
|---|---|
fullFence() | StoreLoad — strongest |
acquireFence() | LoadLoad + LoadStore |
releaseFence() | LoadStore + StoreStore |
loadLoadFence / storeStoreFence | Specific ordering |
8. Understanding Plain vs Opaque vs Volatile Access
| Mode | Atomic? | Ordering | Cost |
|---|---|---|---|
| Plain | No | None | Cheapest |
| Opaque | Per-var | Coherence only | Low |
| Acquire/Release | Yes | One-way | Medium |
| Volatile | Yes | SC-DRF | Highest |
9. Using VarHandle with Arrays
Example: Lock-free counter array
private static final VarHandle AA = MethodHandles.arrayElementVarHandle(long[].class);
public void increment(long[] arr, int i) {
long cur;
do { cur = (long) AA.getVolatile(arr, i); }
while (!AA.compareAndSet(arr, i, cur, cur + 1));
}
| Operation | Use |
|---|---|
| getVolatile | See latest value |
| compareAndSet | Lock-free update |
| getAndAdd | Counter increment |
10. Combining VarHandle with MethodHandle
| Pattern | Use |
|---|---|
| VarHandle as MH | vh.toMethodHandle(AccessMode.SET) |
| CAS in MH chain | Compose with insertArguments |
| Generated bytecode | Use both for high-perf lock-free structures |