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 thatunsafeLazyInitializationis actually safe ifResourceis immutable.)
For the 2nd part of this question, it is discussed in detail in another question (click here)
Yes, you are correct, there is a data race.
Only the
ImmutableObjectis immutable and can be shared safely between threads, yourList, however, does not have these same guarantees, so there is a data race between adding theImmutableObjectand retrieving it.In JCIP, the authors meant immutable objects are safe to publish in the sense that you don’t have to worry about doing things like making defensive copies.
As to:
This statement means that given 2 threads with an immutable object
Athat they both acquired through any means, they can both use objectAwithout worrying about thread-safety issues.