In Java Concurrency In Practice, the author stated that
- Immutable objects can be published through any mechanism
- Immutable objects can be used safely by any thread without additional synchronization, even when synchronization is not used to publish them.
Does it mean that the following idioms are safe to publish immutable objects?
public static List<ImmutableObject> list = new ArrayList<ImmutableObject>();
// thread A invokes this method first
public static void methodA () {
list.add(new ImmutableObject());
}
// thread B invokes this method later
public static ImmutableObject methodB () {
return list.get(0);
}
Would there be any data race? (which means thread B may not be able to see the Immutable Object in the list added by thread A)
Thank you very much.
More, the author said that the following code is safe if Resource is immutable.
@NotThreadSafe
public class UnsafeLazyInitialization {
private static Resource resource;
public static Resource getInstance() {
if (resource == null)
resource = new Resource(); // unsafe publication
return resource;
}
}
Section16.3 The guarantee of initialization safety allows properly constructed immutable objects to be safely shared across threads without synchronization, regardless of how they are published even if published using a data race. (This means that
unsafeLazyInitialization
is actually safe ifResource
is immutable.)
For the 2nd part of this question, it is discussed in detail in another question (click here)