volatile vs synchronized

Java Notes [4]

John Lu
1 min readFeb 19, 2023

Let’s take a look at some important definitions of locks and synchronization.

  1. Thread safe: It means that a method or class instance can be used by multiple threads at the same time without any problem.
  2. Mutual Exclusion: It means that only one thread or process can execute a block of code (critical section) at a time.
  3. Visibility: It means that changes made by one thread to shared data are visible to other threads.

synchronized

Java’s synchronized keyword guarantees both mutual exclusion and visibility. If we make the blocks of threads that modify the value of the shared variable synchronized only one thread can enter the block and changes made by it will be reflected in the main memory. All other threads trying to enter the block at the same time will be blocked and put to sleep.

volatile

Volatile variables have the visibility features of synchronized but not the atomicity features. The values of the volatile variable will never be cached and all writes and reads will be done to and from the main memory. However, the use of volatile is limited to a very restricted set of cases as most of the times atomicity is desired.

Reference

--

--

John Lu

AI Engineer. Deeply motivated by challenges and tends to be excited by breaking conventional ways of thinking and doing. He builds fun and creative apps.