java - 在同步块内重新排序
是否可以对同步块内的语句进行重新排序?例如
synchronized(lock) {
statement1;
statement2;
}
,其中statement1和statement2彼此不依赖。处理器或编译器可以对这些语句重新排序吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,如果优化器决定的话,这些语句可以在同步块内重新排序。但它们不能脱离
同步
。Yes these statements can be reordered within
synchronized
block if optimizer decides so. But they can't be taken out ofsynchronized
.如果编译器(实际上是优化器)确定不会产生副作用,那么它可能会重新排序,甚至消除代码(例如分配给在超出范围之前不会被引用的变量)加快速度。这只会发生在同步块本身内。
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.
根据 JSR-133,同步块内的语句不能重新排序:
http://www.cs.umd.edu/ ~pugh/java/memoryModel/jsr-133-faq.html,“同步的作用是什么”部分
“线程中的每个操作都发生在该线程中按程序顺序稍后出现的每个操作之前。”
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."