I have a question about code reordering and race conditions in Java.
Assume I have the following code, with 2 or more threads simultaneously executing 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? For example, is the following reordering possible?:
sharedObject++;
lock.lock();
lock.unlock();
Or is it guaranteed that the lock will not be reordered?