Example pre-Java 5 lock implementation

As part of our discussion of locking mechanisms in Java 5, here's a rough example of how you could implement an interruptable, re-entrant Lock object pre-Java 5, using the wait/notify idiom.

Note that the purpose of this example is to give a very rough idea, basically to say "you could do it but it was ugly".

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();
      }
    }
  }
}

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.