问题
While reading "Java Concurrency in Practice", I came across the following -
To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:
- Initializing an object reference from a static initializer;
- Storing a reference to it into a volatile field or AtomicReference;
- Storing a reference to it into a final field of a properly constructed object; or
- Storing a reference to it into a field that is properly guarded by a lock.
My question is - is the second point true? I.e. Can I make an Object's state visible to other threads just by storing a reference to it in a volatile reference? If not, am I reading the above points incorrectly?
回答1:
Making object volatile doesn't make his state published to all the Threads, ie
volatile A a = new A();
private static class A {
int i = 0;
int j = 0;
int k = 0;
}
is not the same as
A a = new A();
private static class A {
volatile int i = 0;
volatile int j = 0;
volatile int k = 0;
}
(1) rather makes your reference volatile, ie if one Thread reassigns the reference, this reassignment will be "published" to other Threads immediately
来源:https://stackoverflow.com/questions/36200870/does-a-volatile-reference-really-guarantee-that-the-inner-state-of-the-object-is