1 / 3

Locking in Java

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 (); }.

merry
Télécharger la présentation

Locking in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Locking in Java

  2. 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?

  3. 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

More Related