40 likes | 151 Views
Locking in Java. The ReentrantLock class. ReentrantLock lck = new ReentrantLock (); void withdraw(long amt) throws Exception { lck.lock (); try { do stuff… } finally { lck.unlock (); } } void deposit(long amt) { lck.lock (); balance= balance+amt ; lck.unlock (); }.
E N D
The ReentrantLock class ReentrantLocklck=new ReentrantLock(); void withdraw(long amt) throws Exception { lck.lock(); try { do stuff… } finally { lck.unlock();} } void deposit(long amt) { lck.lock(); balance=balance+amt; lck.unlock(); } Why the ‘finally’ block for withdraw and not deposit?
Java’s synchronized statement void withdraw(long amt) throws Exception { synchronized(this) { do stuff… } } void deposit(long amt) { synchronized(this) { balance=balance+amt; } } The block of code covered by ‘synchronized’ will lock on the object passed in; almost always ‘this’ for convenience With ‘synchronized’ we are guaranteed that leaving that block of code will release the lock, even if the code throws an exception or returns