Amazon Interview Question
Software Engineer / Developerspublic 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();
}
}
}
}
- jzhu May 20, 2012