Presentation is loading. Please wait.

Presentation is loading. Please wait.

Locking in Java.

Similar presentations


Presentation on theme: "Locking in Java."— Presentation transcript:

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


Download ppt "Locking in Java."

Similar presentations


Ads by Google