The Synchronized and Volatile Keywords
Explore how the synchronized and volatile keywords in Java help manage thread safety by ensuring atomicity and visibility in multi-threaded environments. Understand their differences and practical uses to coordinate shared state access effectively, preparing you for complex concurrency challenges.
We'll cover the following...
When multiple threads access shared mutable state, we need to coordinate access and ensure that updates made by one thread are visible to others. Two key concerns in concurrent programming are atomicity and visibility. Java provides language features such as synchronized and volatile to address these concerns.
Let’s explore the synchronized and volatile keywords and how they protect our code:
What is the synchronized keyword?
Note on virtual threads: In earlier Java versions (like Java 21), a virtual thread executing inside a
synchronizedblock could pin its underlying carrier platform thread, temporarily reducing application throughput. As of Java 24 and Java 25 LTS, the JVM has resolved this pinning issue. Virtual threads now fully support ... ...