Temple Wing
Temple Wing

Reputation: 433

How to know whether an explicit lock has successfully provided memory visibility?

This is code is copied from internet somewhere:
How can this explicit lock work?

public class Lock {
  private Object lockObj = new Object();
  private Thread owner;
  private int lockCount;

  /**
   * Waits for up to 'maxWait' milliseconds to acquire the lock,
   * and returns true if the lock was acquired.
   **/
  public boolean acquireLock(int maxWait) throws InterruptedException {
    Thread currentThread = Thread.currentThread();
    synchronized (lockObj) {
      if (owner == currentThread) {
        lockCount++;
        return true;
      }
      long waitedSoFar = 0L;
      while (owner != null) {
        long t0 = System.currentTimeMillis();
        long timeToWait = maxWait - waitedSoFar;
        if (timeToWait <= 0)
          return false;
        lockObj.wait(timeToWait);
        if (owner != null) {
          waitedSoFar += System.currentTimeMillis() - t0;
        }
      }
      owner = currentThread;
      lockCount = 1;
      return true;
    }
  }
  public void releaseLock() {
    Thread currentThread = Thread.currentThread();
    synchronized (lockObj) {
      if (owner == currentThread) {
        lockCount--;
        if (lockCount == 0) {
          owner = null;
          lockObj.notify();
        }
        return;
      } else {
        // Only the owner can release the lock!
        throw new IllegalStateException();
      }
    }
  }
}

I haven't seen any special code to guarantee memory visibility. The only thing related to concurrency is "synchronized(lockObj){ ... }"

Is that magic?
Does a CPU just flush all its cache before acquire some synchronization monitor?
Or the opposite?
Does a CPU just flush all its cache when release some synchronization monitor?

EDIT:
Well, I got some other thing related to concurrency wait/notify.

Think about it. How does this explicit lock working?

  1. acquire the lock, modify variable(to prevent other thread to acquire it), then release the lock.
  2. do anything.
  3. acquire the lock,modify variable(to allow other thread to acquire it).
  4. some other thread acquire the lock, and loop...

The happens-before relationship is just between 3 and 4 right?
Or does between 1 and 3 also be guarantee happens-before relationship? So 2 is guaranteed memory visibility?

Upvotes: 1

Views: 107

Answers (1)

Femaref
Femaref

Reputation: 61437

There is no such thing as a synchronisation monitor that a cpu can acquire. A monitor is a contruct implemented in the runtime of the language you are programming in, in this case, java.

The java runtime is responsible for this locking and forbidding other code to enter the synchronized block of code. The cpu just sees instructions that deal with it.

Concerning your question of cache: The cpu doesn't just decide to flush the cache. The cache stays in place until it is overwritten.

Upvotes: 1

Related Questions