Coming from C/C++, I am a little confused about volatile object behavior in Java.
I understand that volatile in Java has two properties:
- Won't bring object into cache, always keep it in main memory.
- Guarantee "happen-before"
However I am not sure what happens if I make a new non-volatile reference to object. For example,
class Example {
private volatile Book b = null;
public init() { b = new Book(...); }
public use() {
Book local = b;
local.read();
}
}
AFAIK, volatile means the "book object" that b is referencing to should be in main memory. Compiler probably implement reference as pointer internally, so the b pointer probably sit in cache. And to my understanding, volatile is a qualifier for object, not for reference/pointer.
The question is: in the use method, the local reference is not volatile. Would this "local" reference bring the underlying Book object from main memory into cache, essentially making the object not "volatile"?