"Safe publication is sufficient for other threads to safely access objects that are not going to be modified after publication without additional synchronization.
The safe publication mechanisms all guarantee that the as-published state of an object is visible to all accessing threads as soon as the reference to it is visible,
and if that state is not going to be changed again, this is sufficient to ensure that any access is safe"
That's the point of the example Campbell. The class is thread-safe because it is immutable and published safely. If the 'a' field was not declared volatile (and also not final), B would NOT be thread-safe, even if it is immutable.
Yes it could, but this would incur unnecessary overhead. The synchronized keyword is a heavier tool than the volatile keyword. Besides, you don't need to use the synchronized keyword in the constructor at all if you synchronize access to a in the accessI() method.
I know this is not the point of your question, but as a final (hehe) remark I want to say that if you have an immutable class, you NEVER have to use volatile or synchronized, because you can use final instead and it will make your code faster as well.
One thing that puzzles me in JCIP is when it talks about immutable objects. It says that immutable objects are immune to improper publication.
It gives this example :
In another class, you've got
It says this is publishing an object without adequate synchronization. But it says that making n in Holder final would make the class immutable and would then be immune to improper publication. But you'd still need to make the holder ref volatile - or employ anothre synchonization mechanism - so that reading threads would see the right object ?!!? In other words you'd need to publish it properly. Can someone resolve my confusion ?! Thanks