Reputation: 3620
I am reading "Java Concurency in Practice" by Brian Goetz, and have a question about immutable object publication.
In section 3.5.5 it states:
Immutable objects can be published through any mechanism.
Effectively immutable objects must be safely published;
As an example for my question:
// assume Holder is immutable
public class Test {
public static Holder holder = null;
}
Suppose a thread executes the statement:
Test.holder = new Holder(42);
Does this change (i.e. both the reference and the immutable Holder object together) become visible to other threads?
It would seem the semantics, if I'm understanding the textbook correctly, are similar to volatile variables in the sense that the update to the Test.holder
member specifically is visible to other threads immediately?
Upvotes: 1
Views: 120
Reputation: 51542
The modification made to the reference variable Test.holder
is not guaranteed to be seen by other threads immediately. To ensure this, you have to declare it as volatile
. Then, writes to Test.holder
become visible immediately.
What is meant in the text is that if you initialized the Test.holder
with a new Holder(42)
instead of null
and never changed it, then all threads would see that Holder(42)
object.
Upvotes: 2