public class Lock { private boolean used; public Lock(){ this.used = false; } public Lock(boolean used){ this.used = used; } /* Try to take the lock (non-blocking). */ public synchronized boolean tryTake(){ if( used ){ return false; } used = true; return true; } /* Take the lock (blocking). */ public synchronized void take() { while( used ){ try { wait(); } catch(InterruptedException e) {}; } used = true; } /* Leave the critical section. */ public synchronized void release(){ if( !used ){ throw new RuntimeException("trying to release the lock while free"); } used = false; notify(); } }