• Post Reply Bookmark Topic Watch Topic
  • New Topic

Concept of ReentrantLock in Java  RSS feed

 
Siddharth Bhargava
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.

Thanks
Sid
 
Campbell Ritchie
Marshal
Posts: 55770
163
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!