Download presentation
Presentation is loading. Please wait.
1
Locking in Java
2
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) balance=balance+amt; lck.unlock(); Why the ‘finally’ block for withdraw and not deposit?
3
Java’s synchronized statement
void withdraw(long amt) throws Exception { synchronized(this) { do stuff… } } void deposit(long amt) { 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.