问题
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.
回答1:
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.
回答2:
ReentrantLock
can be used for timeout requirements. Suppose you are trying to acquire a lock but the lock is already taken at that point of time you can use tryLock()
which will return immediately and later you can try again.
ReentrantLock
has some other advantage of being provide fairLock or unFair by its con structure:
public ReentrantLock(boolean fair)
if you put the fair
as false
than it will not provide you a lock with fair ordering. And unfair ordering out performs the fair lock. I can explain this if you need more details.
But the problem with ReentrantLock
is, it is hard to debug because in the logs it can't explain about the owner of the lock but in synchronized it is possible. It's the biggest disadvantage.
you can implement features like dining philosopher with this locking mechanism. If both sticks are available than go ahead and eat else drop the one which you are currently holding.
public void run() {
while (!Thread.currentThread().isInterrupted()) {
if (l.getLeftLock().tryLock()) {
try {
if (r.getRightLock().tryLock()) {
try {
System.out.println("Eating philosopher1 !!!!");
} finally {
r.getRightLock().unlock();
}
}
} finally {
l.getLeftLock().unlock();
}
}
try {
Thread.currentThread().sleep((int) (100 * Math.random()));
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
回答3:
For the ReentrantLock
class, compared to plain synchronized
in my opinion the key benefits are:
- acquire/release the lock in different blocks.
- have fair locks (FIFO for the waiting threads)
- can try to lock
- can have multiple condition variables
Also, a bit off-topic, but for understanding the java concurrent classes, i found Java Concurrent Animated very useful. Download the runnable jar file and see for your self.
回答4:
Take a look at: https://stackoverflow.com/a/1312282/668951 Also in my case I read about it in Henry Wong's book though not in great detail.
来源:https://stackoverflow.com/questions/19721197/reentrantlock-use-case