Does a synchronized keyword prevent reordering in Java?

Suppose I have the following code in Java

a = 5;
synchronized(lock){
    b = 5;
}
c = 5;

Is reordering prevention synchronized? There is no relationship between a, b, and c. Will the assignment be first, then b, and then c? If I am not synchronized, the operators can be reordered in any way, does the JVM choose correctly?

+4
source share
3 answers

Is reordering prevention synchronized?

This prevents some reordering. You can still reorder outside the synchronized block and inside the synchronized block, but not inside the synchronized block, outside it.

a, b c.

.

, b, c?

. , , JVM. (. )

, - , JVM ?

, JVM / / , , , a = 5; b = 5; .

, . , , b = 5; = 5; , .

+4

b , , .

, , .

↓ ↑:

a = 5;
b = 5;
c = 5;

↓ . ↑ .

+5

?

, . .

, b, c?

. dcastro, . , , :

synchronized (lock){
    a = 5;
    b = 5;
    c = 5;
}

, . , :

synchronized (lock){
    c = 5;
    b = 5;
    a = 5;
}

, - , JVM ?

, , , Java. Java , . , . , , §17.4.5 Java:

, . , .

In other words: if you completely ignore reordering and for all possible program executions, there is no way for two threads to access the same memory location, which is neither mutable nor atomic, and at least one of the actions is a write operation, then all performances will be displayed as if there were no changes.

In short: Avoid data investigations and you will never see reordering.

+2
source

Source: https://habr.com/ru/post/1537922/


All Articles