Reputation: 1445
I have read about marking an object as volatile doesn't guarantee visibility of it's members ( I'm not saying about thread safety just memory visibility , quoting :
only the object reference will be considered to be volatile by the JVM and not the object data itself which will reside on the heap
my questions :
Sample code:
class Test{
volatile Data data;
}
Class Data{
int x;
int y;
}
data= new Data(); // happens-before relationship only on creation
//writer
Thread writerThread = new Thread(() -> {
data.setX(a);
data.setY(b);
});
//reader
Thread readerThread = new Thread(() -> {
// read here is not guaranteed visibility, x,y not volatile
int x = data.getX();
int y = data.getY();
});
Upvotes: 3
Views: 701
Reputation: 28269
happens-before
relationship will gurantees that. While volatile keyword also builds happens-before
relationship between the write thread and the read thread.Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.
Upvotes: 1