java - reordering inside synchronized block
Is it possible for the reordering of statements inside a synchronized block ? For example
synchronized(lock) {
statement1;
statement2;
}
In which, statement1 and statement2 are not dependent on each other. Can the processor or comp开发者_运维百科iler reorder these statements ?
Thank you.
Yes these statements can be reordered within synchronized
block if optimizer decides so. But they can't be taken out of synchronized
.
The compiler (optimizer, actually) might reorder things, or even eliminate code (like assigning to a variable that is not going to be referenced before going out of scope) if it knows of a certainty that there would be no side effects and it would speed things up. That will only happen within the synchronized block itself.
According to JSR-133, statements inside the synchronized block can not be reordered: http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html, "What does synchronization do" section
"Each action in a thread happens before every action in that thread that comes later in the program's order."
精彩评论