0

Consider the following example:

Thread 1:

data.a = 1;
synchronized (sth) {
    shared = data;
}

Thread 2:

synchronized (sth) {
    assertEquals(1, shared.a);
}

Assume that the code in Thread 2 gets executed after the code for Thread 1.

Is the assert guaranteed to succeed, ie. does the memory barrier inherent to the lock release in thread #1 extend to the assignment of the value 1 before and outside of the synchronized block?

user1050755
  • 11,218
  • 4
  • 45
  • 56
  • Didn't you ask [this same question](http://stackoverflow.com/questions/40913091/using-java-object-refs-for-inter-thread-communication-utilizing-synchronized-blo?noredirect=1#comment69038424_40913091) just a short while ago? – Andy Turner Dec 01 '16 at 14:59
  • I removed the notify/wait stuff because it made ppl think about the wrong question and deleted the previous question. – user1050755 Dec 01 '16 at 15:00
  • Yes. Also true without `synchronized` if `shared` is `volatile` – ZhongYu Dec 01 '16 at 15:33
  • Only if that assumption holds. But you can't guarantee that it will. You might have `data.a = 1;` execute in `Thread 1`, then `synchronized(sth)` and `assert` in `Thread 2`, failing. Then `synchronized(sth)` and the assignment in `Thread 1`. – Sotirios Delimanolis Dec 01 '16 at 15:47

0 Answers0