Marin Veršić
Marin Veršić

Reputation: 403

Synchronized reordering in java

It is known that JVM shouldn't reorder statements from withing synchronized block to outside of the synchronized block. Considering this, is JVM allowed to reorder assignment y = 7 to occur after the synchronized block in the following snippet?

x = 5;
y = 7;
synchronized (this) {
    x = 6;
}

We know that variable assignment before the synchronized block can be reordered to occur inside the block. So the following should be valid reordering of the initial code:

x = 5;
synchronized (this) {
    x = 6;
    y = 7;
}

One could argue that, because this is a valid ordering, y assignment cannot occur after the synchronized block as it would violate the rule that code from within synchronized block mustn't be reordered to occur after the block and deduce that y happens-before end of the synchronized block.

On the other hand, it could be that all orderings are not equivalent and it matters which ordering was the actual ordering. Specifically, if y assignment was originally done within the synchronized block it couldn't occur after the block, otherwise it could.

To sum up, is next ordering valid ordering of the first snippet?

x = 5;
synchronized (this) {
    x = 6;
}
y = 7;

Upvotes: 4

Views: 226

Answers (2)

JLS 17.4.5:

  • If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).

...

  • If an action x synchronizes-with a following action y, then we also have hb(x, y).

Your question only makes sense when including the assumption that the value of y could be visible outside the current thread. If that's the case, the combination of these two rules requires that the assignment not be reordered after the synchronized block.

Upvotes: 5

Eugene
Eugene

Reputation: 120848

Yes, your reasoning are flawed; this can not happen.

A monitor enter is like a volatile load (not entirely correct, but I understand it simpler like that - there will be two barriers inserted : LoadLoad|LoadStore) and operations that are before that can not float across that barrier.

I am pretty sure, this is specified by the JLS and while I wanted to link to that, the other answer has already did - go upvote it.

Upvotes: 0

Related Questions