Home  Synchronization and concurrency  wait/notify  final  volatile  synchronized keyword  Java threading  Deadlock (and avoiding it)  Java 5: ConcurrentHashMap  Atomic variables  Explicit locks  Queues  Semaphores  CountDownLatch  CyclicBarrier

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

Article written by Neil Coffey (@BitterCoffey).

Software

 LetterMeister (word puzzle game for iPhone)
 Currency Quoter (currency converter/predictor)
 French Vocab Games for iPhone/iPad
 Vocabularium: create Spanish vocab podcasts


Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey). Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Neil Coffey 2014. All rights reserved.