Java 9 VarHandles Best practices, and why?
summary
Java 9 VarHandles provide atomic operations and fine-grained memory ordering on any field type (instance/static/array/bytebuffer) as a safe replacement for sun.misc.Unsafe and some Atomic types. API exposes five access modes (plain, opaque, release/acquire, volatile) plus fences (load/load, store/store, release, acquire, full) so code can merge sync points or use weaker ordering for speed. Best practices: declare the handle private static final*, back fields volatile to fail fast on mistakes. JVM work aims for Unsafe-level codegen (example reducing three sets to three move instructions), optimization still in progress.
AI-written summary · about
chapters (15)
- 0:00Introduction and agenda
- 1:38Understanding memory models
- 9:23Key memory model rules
- 13:45Synchronization trade-offs
- 15:28Limitations of old solutions
- 16:44Introducing VarHandles
- 18:48VarHandle access modes
- 19:27How to create VarHandles
- 20:21Coding tips and practices
- 24:02Memory ordering modes
- 30:21Using fences
- 31:05Fence examples and benefits
- 34:55Comparison with unsafe
- 36:02Performance goals
- 37:18Conclusion and Q&A








