What is a deadlock?

  • A deadlock is a deadlock (Deadly Embrace) in which two or more processes (threads) compete for resources while running, and none of them can move forward without an external force.

A few conclusions about deadlocks:

  • At least two processes must be involved
  • Participating deadlock all processes are waiting for resources
  • At least two processes participating in the deadlock have already occupied resources
  • A deadlocked process is a subset of the set of processes in the current system
  • Deadlocks can waste a lot of system resources and even cause system crashes

To be sure, I started calling getLock1 and getLock2 in the main() method, and I wondered why the two methods didn’t compete

Method :” Deadlocks on the main thread”

In fact, the thread creates a race, the thread simultaneously holds and waits for us to create the condition

In the program, we let Thread-1 hold lock1 and request lock2

Let Thread-2 hold lock2, requesting lock1 complies with both hold and wait

public class ZDeadLock {

  private static final Object lock1 = new Object();

  private static final Object lock2 = new Object();

  public static void main(String[] args) {
    new Thread(
            new Runnable() {
              @Override
              public void run(a) {
                getLock1();
              }
            })
        .start();

    new Thread(
            new Runnable() {
              @Override
              public void run(a) {
                getLock2();
              }
            })
        .start();
  }

  public static void getLock2(a) {
    synchronized (lock1) {
      System.out.println("Hold lock1, wait to acquire lock2..");
      synchronized (lock2) {
        System.out.println("Obtained lock2"); }}}public static void getLock1(a) {
    synchronized (lock2) {
      System.out.println("Hold lock2, wait to acquire lock1..");
      synchronized (lock1) {
        System.out.println("Obtained lock1"); }}}}Copy the code

After the operation is indeed a long infinite wait, no longer access to

Jvisualvm opens at this point, flashes and tells us that a deadlock has occurred

In this case, thread dump prints information about deadlocks

With this in mind, the next time a deadlock occurs in a program, you’ll know why