As per Java Concurrency in Practice below code can throw assertion Error:
If a thread other than the publishing thread were to call assertSanity, it could throw AssertionError
public class Holder {
private int n;
public Holder(int n) { this.n = n; }
public void assertSanity() {
if (n != n)
throw new AssertionError("This statement is false.");
}
}
// Unsafe publication
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
Question is: If I save, an object which refers to other objects in a ConcurrentHashMap, is there a possibility that certain updates on this object graph will not be in sync, in a multi-threaded environment due to same reasons as mentioned for above example?
Though root node in object graph will always be updated in map for all threads, but what about other objects which are referred as fields in root node, if these are not final or volatile ?
Answering my own question, I should have read complete chapter before asking question. This is what later part of chapter says:
Mutable objects: If an object may be modified after construction, safe publication ensures only the visibility of the as-published state. Synchronization must be used not only to publish a mutable object, but also every time the object is accessed to ensure visibility of subsequent modifications. To share mutable objects safely, they must be safely published and be either thread-safe or guarded by a lock.
So using CHM or any thread safe collection is unsafe in a multithreaded environment, unless you synchronize changes to your mutable objects in CHM or these objects are immutable.
A ConcurrentHashMap guarantee that all operation with reference (link to object), that be saved in a ConcurrentHashMap, are thread-safe, however, of course, a ConcurrentHashMap can not guarantee a thread-safe every objects, with reference(link) be stored in a ConcurrentHashMap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With