我有一个
Java代码重新排序和竞争条件的问题.
假设我有以下代码,同时执行2个或更多的线程workForThread():
public class Job { private Lock lock = new ReentrantLock(); private int sharedObject = 1; public void workForThread() { lock.lock(); try { sharedObject++; } finally { lock.unlock(); } } }
JVM是否可能以错误的顺序执行?例如,以下是否可以重新排序?
sharedObject++; lock.lock(); lock.unlock();
还是保证锁不会重新排序?
解决方法
我们来看看Java文档关于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: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.
所以你的问题的答案是肯定的.锁定给你同样的重新排序保证,一个常规的同步块/方法会.