Case of using ReentrantLock

I am very poorly versed in the concept of MultiThreading Java.

I went through the functions and use of ReentrantLock. I realized that it is more flexible and then synchronized and adds a few more features.

I see the examples mentioned on it, and I got it well.

I cannot understand the real-time scenario where exactly this will be useful in business.

I see that it is better to avoid deadlocks.

Can someone provide a use case where without ReentrantLock it would be difficult to solve such a use case.

or may point to some link.

+4
source share
4 answers

, / , .

A -, / (). /. , () .

+2

ReentrantLock . , , , tryLock(), , .

ReentrantLock : fairLock unFair con:

public ReentrantLock(boolean fair)

fair false, . . , .

ReentrantLock , , , . .

, . , , , .

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();
        }
    }
}
+4

ReentrantLock, synchronized, , :

  • / .
  • (FIFO )

, , java- Java Concurrent Animated . runnable jar , .

+1

All Articles