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?
Let's take a look at what the Java Docs says about the Lock
interface :
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.
So the answer to your question is yes. Lock
gives you the same reordering guarentee that a regular synchronized
block/method would.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With