Understanding Java Concurrency: Volatile, Synchronized, JMM, and MESI
This article provides a comprehensive tutorial on Java concurrency, covering the usage and implementation principles of the volatile and synchronized keywords, the Java Memory Model, the MESI cache protocol, common visibility and reordering issues, and practical code examples for designing efficient multithreaded solutions.
The tutorial introduces the goals of a Java concurrency learning session, outlining common tools and classes, their implementation ideas, typical problems, and how to select appropriate mechanisms for efficient design.
Volatile keyword is presented with its usage (e.g., private volatile long value; ) and its two main effects: guaranteeing global visibility of a variable and preventing instruction reordering.
An illustrative example shows a race where only one thread perceives a start flag due to each thread having its own cache copy; after adding volatile , all threads see the change, demonstrating visibility handling via the Java Memory Model (JMM) and underlying hardware.
The article then explains the JMM and the MESI cache‑coherency protocol, describing how variables are stored in main memory, copied to thread‑local caches, and how state transitions (Exclusive, Shared, Modified, Invalid) enable visibility guarantees.
Implementation details of volatile are shown: the compiler inserts a lock addl instruction that forces the CPU to write back the cache line to main memory, ensuring other processors observe the update.
Synchronized keyword usage is demonstrated for methods and code blocks, with bytecode excerpts showing the ACC_SYNCHRONIZED flag, monitorenter , and monitorexit instructions. The relationship between monitors, object headers, and lock states (biased, lightweight, heavyweight) is explained.
The lock upgrade process—from biased to lightweight to heavyweight—is illustrated with diagrams, and design principles are summarized: avoid locks when possible, prefer biased locks for low contention, and switch to heavier locks under high contention.
Finally, a post‑lecture exercise asks readers to implement a CAS‑based lock with performance goals for single‑thread, low‑contention, and high‑contention scenarios, and provides references to further reading such as "Java Concurrency in Practice".
TAL Education Technology
TAL Education is a technology-driven education company committed to the mission of 'making education better through love and technology'. The TAL technology team has always been dedicated to educational technology research and innovation. This is the external platform of the TAL technology team, sharing weekly curated technical articles and recruitment information.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.