Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Concept of ReentrantLock in Java

Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

I am learning the topic ReentrantLock in Java. I am referring the book Core Java by Cay S. Horstmann. I have understood the following uptill now as given in the book:

It guarantees that only one thread at a time can enter the critical section. As soon as one thread lock the lock object, no other thread can get past the lock statement. When other threads call lock, they are blocked until the first thread unlock the lock object.

My Doubt:

1) I am unable to understand a simple example of ReentrantLock though I have searched a lot of examples from the net. I don't want to do rote learning, instead I want to understand the concept behind RenetrantLock with a simple pratical example. Could anyone please help me with the same ?

2) Also help me with some real world example where RenetrantLock are being used.

Posts: 69894
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The lock is an object which (would you believe) holds a lock. The reason for writing try‑finally is that you must ensure the lock is unlocked whatever happens. If an Exception occurs somewhere and it is caught elsewhere, then the lock will remain locked and the only way you can unlock it is to terminate the JVM and start again. Remember code inside a finally is always executed whether or not an exception is thrown.
You can use a reentrant lock wherever you lock methods. It appears in its full glory when you are calling methods from other methods.You go into one method and lock is locked. That calls another method and you are now locked ×2. When you get to the 3rd method you are locked ×3. If you got into the zizz method by a different route, you might be locked once there, or locked ×5, but not 2147483648× . As long as you have the unlock call in a finally, you will completely unlock the lock when the last method completes. The lock belongs to the current Thread, until it is completely unlocked, when another Thread can take ownership.
Stop it! You're embarassing me! And you are embarrassing this tiny ad!
Thread Boost feature
    Bookmark Topic Watch Topic
  • New Topic