简体   繁体   中英

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 compiler 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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM