|
|
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 implementationAs 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
Copyright © Neil Coffey 2013. All rights reserved. |