I am very poor in MultiThreading concepts of Java.
I was going through ReentrantLock features and usage. I got that it is more flexible then synchronized and adds few more features.
I can see the examples mentioned on it and I got it well.
I am not able to figure out the real time scenario where exactly it will be helpful in business.
I can see that it will be best to avoid deadlocks.
Can some one provide the use case where without ReentrantLock it will be difficult to solve such use case.
or can point to some link will be helpful.
A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.
Lock is an interface. It defines a set of methods that all locks should have. ReentrantLock is a concrete class that implements the Lock interface.
In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock.
According to Sun Microsystems, Java monitors are reentrant means java thread can reuse the same monitor for different synchronized methods if method is called from the method.
For a simple case how about timed lock / or partial lock for a application which demands performance.
A Very common example would be online portals which let you buy/book tickets(any). You get a timed lock on the seat/resource you are interested in. After the time expires and if transaction is not completed any other client application(thread) can acquire lock on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With