Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Java volatile field
1. Volatile Fields
What is Volatile ?
Volatile is a keyword in java which can only be apply to java primitive data types e.g. int,
boolean, float, double etc.
What is the use of Volatile field ?
One threads writes variable value to the Memory can be seen by other thread, but there
is no guarantee which value will be read by other thread. There should be some explicit
communication to gaurntee so that particular writes can be read by other thread.
The volatile keywords or modifier in front of variable tells the JVM that a thread accessing
the variable must always reconcile(check) its own private copy of the variable with the
master copy in memory.
Example :
Assume foo1 is a volatile boolean variable initialized to false, and foo2 is a non-volatile int
variable initialized to 0. And also assume there are two threads Thread1(Which is called
sender) and Thread2(Called Receiver).
If foo1 and foo2 both are non-volatile then ?
So JVM does not gaurntee which value would be read by othere thred. Now consider the
case where foo1 is updated by Thread1 to true. And thread2 is reading value foo1 as true
but somehow the priavate value of foo2 is not updated in context of thread2 (Non volatile
so no gaurntee when will be updated). So thread2 will print foo2 as a 0 instead of 50.
If foo1 and foo2 both are volatile then ?
The first thread(Thread1) writes to foo1=true, which is going to be the sender side of the
communications. The second thread(Thread2) reads foo1=true and sees the value the first
2. thread wrote to it. Hence Thread2 becomes a receiver. Because foo1 and foo2 is volatile
hence the value read by second thread will always be updated one, all of the memory
contents seen by Thread 2, will be updated.This guarantees that Thread 2 will print "50", if
it prints anything at all.
if there are more thread involved then also JVM gaurntees that receiver thread will always
get a updated value.
When to use and not use volatile?
Not use
● For final field volatile should not be used.
● Volatile is not necessary for variables that are accessed by only one thread.
● Place where X++ is not involved (Because this is not a single instruction).
Use
● Such as above you write a variable in one thread and check that variable in another
thread;
● plase where you loosing an update does not affect youroperation.
However, code using volatile is often more fragile than code using locking. In case of
volatile we should consider the use of atomic object like <tt>AtomicInteger</tt>.
Important :
● Before Java 1.5 volatile was not completely suported on 64 bit machine.
● Volatile field means give instruction Hotspot/JVM not to read field from registers read
from RAM updated one.
Author : Ashish Shah (Software Engineer)
email: pappupass.india@gmail.com
PappuPass Learning Resources