Welcome to The 16th article in this series on Concurrency.

In the previous article, “Platinum 1: Tracing the Roots – Why the Lock Interface is the Foundation of Locking in Java,” we covered the reentrant problem of locks and gave a brief introduction. Since lock reentrant is an important concept, this article will give you a separate tutorial to help you fully understand it.

One, the lock can re-enter the problem caused by

First, let’s look at how lock reentrancy causes problems with a sample code to understand its importance.

public class ReentrantWildArea {
    // Field lock
    private boolean isAreaLocked = false;

    // Enter wild area A
    public synchronized void enterAreaA(a) throws InterruptedException {
        isAreaLocked = true;
        System.out.println("Entering wild area A...");
        enterAreaB();
    }
    // Enter the field B
    public synchronized void enterAreaB(a) throws InterruptedException {
        while (isAreaLocked) {
            System.out.println("Field B method is on hold...");
            wait();
        }
        System.out.println("Entering wild area B...");
    }

    public synchronized void unlock(a) {
        isAreaLocked = false; notify(); }}Copy the code

In the above code, we create A field containing fields A and B. Next, let’s create a wild hero armor, let him go into the wild area to fight wild, see what happens.

public static void main(String[] args) {
  // Fight the wild hero armor to enter the wild area
  Thread kaiThread = new Thread(() -> {
    ReentrantWildArea wildArea = new ReentrantWildArea();
    try {
      wildArea.enterAreaA();
    } catch(InterruptedException e) { e.printStackTrace(); }}); kaiThread.start(); }Copy the code

The output is as follows:

We're in the wild. A... Field B Method enter waiting...Copy the code

It can be seen from the results that although kai was in the same field, he only entered field A, but failed to enter field B, and was blocked on the half way. Synchronized: isAreaLocked = true: synchronized = synchronized; synchronized = synchronized; synchronized = synchronized;

This is a typical lock reentrant problem. Failure to handle this problem in concurrent programming can result in infinite thread blocking, the equivalent of a deadlock.

Understand the reentrancy of locks

Lock reentrancy means that the lock can be called repeatedly or recursively by threads. It can also be understood as the repeated acquisition of the same lock. Failure to address the reentrant issue of locks can lead to problems similar to deadlocks.

How to avoid the lock reentrant problem

To avoid the lock reentrant problem, you need to pay attention to two aspects:

  • Avoid writing code that requires reentrant lock acquisition.
  • Use reentrant locks if necessary.

Synchronized is reentrant in Java, and the following code does not cause reentrant problems when invoked.

public class WildMonster {
    public synchronized void A(a) {
        B();
    }
    
    public synchronized void B(a) { doSomething... }}Copy the code

However, locks implemented based on the Lock interface do not always support reentrant. In previous articles, we have shown implementations of the Lock interface that do not support reentrant. It is important to keep this in mind when using it in a specific scenario. If you need a ReentrantLock, you can use the ReentrantLock class in Java.

summary

In this article, we reintroduce the lock reentrant problem, why it occurs and how to avoid it. The synchronized keyword in Java supports reentrant of locks, but other display locks do not always support this feature and should be used with caution.

In addition, it is important to note that lock reentrant has an impact on lock performance and is more complex to implement. Therefore, we cannot say whether the lock is reentrant or non-reentrant, it depends on the specific problem.

At the end of the text, congratulations on your another star ✨

The teacher’s trial

  • Check out the ReentrantLock source code to see how it supports reentrant.

Further reading and references

  • “King concurrent course” outline and update progress overview

About the author

Pay attention to [technology 8:30], get the article updates in time. Pass on quality technical articles, record the coming-of-age stories of ordinary people, and occasionally talk about life and ideals. 8:30 in the morning push author quality original, 20:30 in the evening push industry depth good article.

If this article is helpful to you, welcome to like, follow, supervise, we together from bronze to king.