Search code examples
javamultithreadinghappens-before

Java happens-before clarification and how to safely pass an object back and forth between two threads


I would like to establish a simple "protocol" between two threads of using an arbitrary object, not specifically geared towards multi-threading, in a thread-safe manner. The protocol shall be that only ever one of the threads owns the object and only the owner may read/write the object. I read the information about happens-before here, but are not quite sure whether the discussion relates only to individual fields or to whole objects. Are the following two solutions correct for the "ownership protocol"?

1) Use of a BlockingQueue such that the object is passed over to the other thread through the queue.

2) The "arbitray object" is not so arbitrary anymore in that I introduce a

  volatile boolean ownedByThreadA;

with ownedByThreadA being true initially and Thread A is using the object. When done, Thread A writes false into ownedByThreadA. Thread B polls the variable similar to this

while (data.ownedByThreadA) {
  doOtherThings();
}
dealWith(data);

I am rather sure that (1) is a correct solution. I am not so sure for for (2). In particular for (2) I wonder if just one volatile suffices for a correct solution, given the "user protocol" is obeyed.


Solution

  • It is guaranteed that every write done by Thread A before ownedByThreadA = false must be visible to Thread B after it has seen !ownedByThreadA.

    You also have to be careful how you update the data variable itself (if thread b changes it to something else and the member is not volatile itself you've a bug for example), but assuming that both threads work on the same instance you get correct behavior.