Monday, December 2, 2013

Rentrant Lock

Lets read the code snippet below to understand the problem we are trying to solve here.

Line no. 13. The main thread invokes synchMethodA. To be able to do that, the thread, first needs to acquire lock on businessObj object.

Line no. 22. Once it has acquired the lock, it will start executing the block of code inside the method synchMethodA().

Line no. 25. Within method synchMethodA(), the current thread will try to invoke method synchMethodB().

Line no. 28. Since the method synchMethodA() is also marked as synchronized, the current thread will need to acquire the lock on the object on which it invoked this method, which in this case is businessObj.

Since, the main thread is already holding the lock on businessObj object, does it mean that it would need to acquire the lock on businessObj object again?

  • If yes, how will this thread acquire the lock on the object on which it is already holding the lock?
  • If no, then without acquiring the lock, will the current thread execute the block of code inside method synchMethodB()?

These are some of the questions which will get answered in this post.

What do we mean by Re-entrant mutex?


A simple mutex is not reentrant. If a thread is holding the mutex and tries to get it again, it will be stuck. There is not enough information to identify who was holding the mutex earlier. 

In re-entrant mutex, the same thread can acquire the lock multiple times. For example, it acquires the lock once and then, if it needs lock on the same object, it can acquire it again without first releasing it and also without getting blocked. This is called reentrance.

However, the lock must be released the same number of times or else the other threads will not be able to acquire the lock.

Essentially, it comes from the fact that when the thread needs to acquire a lock, it is not easy to identify if it is already holding the lock on that object.

Is the lock obtained through the regular synchronized keyword reentrant?


When to use re-entrant lock?


Things to take care of when using re-entrant lock.


Some examples of how to use re-entrant lock.

References:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html
http://en.wikipedia.org/wiki/Reentrant_mutex