This Q is looking for specific details on how exactly Java makes a volatile
field visible.
The volatile
keyword in Java is used for making a variable "actively" visible to the readers of that variable right after a write operation on it is done. This is one form of happens-before relationship-- makes the results of a write exposed to whoever accessing that memory location of that variable for some use. And when used, makes the read/write operations on that variable atomic-- for long
& double
as well-- R/W to every other var types are atomic already.
I'm looking to find out what Java does to make a variable value visible after a write operation?
Eg.: The following code is from one of the answers on this discussion:
public class Foo extends Thread {
private volatile boolean close = false;
public void run() {
while(!close) {
// do work
}
}
public void close() {
close = true;
// interrupt here if needed
}
}
Reads and writes to boolean literals are atomic. if the method close()
above is invoked, it is an atomic operation to set the value of close
as true
even if it isn't declared as volatile
.
What more volatile
is doing in this code is making sure that a change to this value is seen the moment it happens.
How exactly volatile
is achieving this?
by giving priority to threads with operations on a volatile variable? if so - how, in thread scheduling, or by making the threads-with-read-operations go look up a flag to see whether there's a writer-thread pending? I'm aware that "A write to a volatile field happens-before every subsequent read of that same field." Is it choosing among the threads, the one(s) that have a write operation on a volatile variable before giving CPU time to threads that only read?
If this is managed in thread scheduling level (which i doubt), then running a thread with a write on a volatile field has a bigger effect than it seems.
How exactly is Java managing visibility of volatile
variables?
TIA.