While reading Concurrency in practice I read that:
NoVisibility
demonstrated one of the ways that insufficiently synchronized programs can c
It's not Java specific issue. Processors have caches. Without synchronization processor 1 can read a value into its cache from memory, modify it in its cache but never flush it, then processor 2 reads stale value from memory
Each thread has its own stack, and so its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables in its own memory. The volatile keyword is used to say to the jvm "Warning, this variable may be modified in an other Thread". Without this keyword the JVM is free to make some optimizations, like never refreshing those local copies in some threads. The volatile force the thread to update the original variable for each variable.
Source DZone
Hardware Implementation
This happens due to the processor optimizations that are done for fast access of variables. When the variable is kept in the cache then it is much faster to access than going to memory everytime. So for flushing the cache you need to say volatile
go and flush the cache and rebuild it as this variable is being modified in other thread.
The caching of static
variables is also done, they too are a eligible for caching due to same reason fast access. So yes you need volatile
for static
variables too.
See also:
What does volatile do?
This issue is related to memory visibility
issue of Multithreading.
If you want to read/get value of an object which can be modified by multiple threds; then you need to be careful. Let's take a sample example to stress the point :
public class XYZ{
private String state;
public synchronized setState(..){
//set state
}
public String getState(){
return state;
}
}
Above example doesn't synchronize the getter method which returns the state. So you might get the stale data (even if its static)
Only way to get latest data is either you syncronize the get method or declare state as volatile.
It's saying that in main
the intention is to set number=42
and ready=true
at the same time, but since they were called in this particular order there is a race condition with your ReaderThread
where it could (probably will) print out the number even though we really don't want it to.
They would like you to synchronize those 2 variables to be set together.