[英]Does Lock guarantee a happens-before relationship?
I have a question about code reordering and race conditions in Java.我对 Java 中的代码重新排序和竞争条件有疑问。
Assume I have the following code, with 2 or more threads simultaneously executing workForThread()
:假设我有以下代码,有 2 个或更多线程同时执行
workForThread()
:
public class Job {
private Lock lock = new ReentrantLock();
private int sharedObject = 1;
public void workForThread() {
lock.lock();
try {
sharedObject++;
} finally {
lock.unlock();
}
}
}
Is it possible that the JVM could execute this in the wrong order? JVM 是否有可能以错误的顺序执行此操作? For example, is the following reordering possible?:
例如,是否可以进行以下重新排序?:
sharedObject++;
lock.lock();
lock.unlock();
Or is it guaranteed that the lock will not be reordered?还是保证锁不会被重新排序?
Let's take a look at what the Java Docs says about the Lock
interface : 我们来看看Java Docs关于
Lock
接口的内容:
All Lock implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock, as described in section 17.4 of The Java™ Language Specification:
所有Lock实现必须强制执行与内置监视器锁提供的内存同步语义相同的内存同步语义,如Java™语言规范的第17.4节所述:
A successful lock operation has the same memory synchronization effects as a successful Lock action.
成功的锁定操作具有与成功锁定操作相同的内存同步效果。
A successful unlock operation has the same memory synchronization effects as a successful Unlock action.
成功解锁操作具有与成功解锁操作相同的内存同步效果。
So the answer to your question is yes. 所以你的问题的答案是肯定的。
Lock
gives you the same reordering guarentee that a regular synchronized
block/method would. Lock
为您提供与常规synchronized
块/方法相同的重新排序保证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.