RonR RonR - 2 months ago 13
Java Question

Does a new thread have full memory-visibility of all other threads' previous actions on shared objects?

I have thread A maintaining a data structure (adding, deleting, changing values in a ConcurrentHashMap).

I have thread B listening on a socket and occasionally creating thread C to handle a new client connection.

All thread Cs will only ever read from the ConcurrentHashMap maintained by thread A (never update it).

Is thread C guaranteed to see all updates that were performed by thread A, on the ConcurrentHashMap, before thread C was created/ started by thread B?

(Edited last sentence to make question clearer: only concerned about updates to the ConcurrentHashMap.)

Answer

Is thread C guaranteed to see all updates that were performed by thread A before thread C was created/ started by thread B?

In general (for example, with an ordinary HashMap), No.

But (again in general) if thread C was created by thread A, then the answer would be yes.

(There is a happens-before relation between one thread calling start() on a thread object, and the start of the new thread's run() method. But you have introduced a third thread ... and have not described anything that would give you a happens-before chain from A to B to C.)


However, you are talking about a ConcurrentHashMap here, and concurrent maps have innate memory consistency:

"Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a ConcurrentMap as a key or value happen-before actions subsequent to the access or removal of that object from the ConcurrentMap in another thread."

(From the ConcurrentMap javadoc.)

So, for anything where multiple threads are sharing a ConcurrentHashMap a read-only thread is guaranteed to see updates made by another one ... modulo the documented behavior of iterators.