I was reading about synchronized and volatile in java. Each new article makes me confused. One article said "Java’s synchronized keyword guarantees both mutual exclusion and visibility". I am not sure about the visibility part. Isn't visibility problems solved by volatile in java. Lets consider this small program.
class SharedObj
{
volatile int sharedVar = 6;
public int synchronized getVar(){
return sharedVar;
}
public synchronized setVar(int i){
return sharedVar=i;
}
}
Lets say this is run by 10 threads , 5 for read and 5 by write on same SharedObj object. Here we need both synchronized as well as volatile?
volatile : As every thread will cache the sharedVar in to local cache.
synchronized : one thread at a time.