Skip to main content

Java Concurrency - Volatile


volatile is a keyword in Java. When we declare a variable as volatile it doesn't store in CPU cache. Instead it is put in shared memory.
Because of that multiple threads can access the same memory location and get the updated value. Hence this is considered as a weaker synchronization mechanism.
volatile is not suitable for atomic operations. It is best suited for single operations like a flag.

private volatile boolean completed;

  • Store in main memory. never store in thread locally.
  • Guarantee visibility.
  • Not suitable for atomic operations like read-modify-write.
  • No lock involved.
  • Never block other threads.
  • Suitable for operations like having a flag.
  • Can be used if the value doesn't depend on previous value.
  • Have a performance hit because it doesn't store in cache.
  • Weaker form of synchronization.