Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReentrantLock use case

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.

like image 560
Jayesh Avatar asked Nov 01 '13 05:11

Jayesh


People also ask

What is the use of ReentrantLock?

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.

What is the difference between lock and ReentrantLock?

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.

What is the difference between synchronized and ReentrantLock in Java?

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.

What is Reentrancy in Java?

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.


1 Answers

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.

like image 80
Aniket Thakur Avatar answered Sep 25 '22 02:09

Aniket Thakur