Does Lock guarantee a happens-before relationship?

Ryu :

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?

CKing :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=453352&siteId=1