Document directory
- 2. Improper lock Maintenance
A recent project was written in Java, and two deadlocks caused by calling join () were encountered during debugging, which were concealed. This is recorded.
1. The thread joins itself in a deadlock
public class Starter { public static void main(String[] args) { new DeadThread().start();}}class DeadThread {public DeadThread() {thread = new Thread(new RealThread());}public void start() {thread.start();}private Thread thread;private class RealThread implements Runnable{public void run() {System.out.println("Thread is starting...");try {thread.join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Thread is stopping...");}}}
Thread realthread calls thread. join () is intended to synchronize with another thread (not shown in the sample code), but as the sample code shows, the thread actually points to itself, this forms a strange deadlock situation:A running thread calls join () to wait for its end.
2. Improper lock Maintenance
Compared with the preceding scenario, the following scenario is more common.
import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class Starter {public static void main(String[] args) {DeadThread dt = new DeadThread();dt.start();dt.stop();}}class DeadThread {public DeadThread() {thread = new Thread(new RealThread());lock = new ReentrantLock();}public void start() {thread.start();}public void stop() {lock.lock();try {// do some real works...running = false;thread.join(); // (2)} catch(Exception e) {e.printStackTrace();} finally {lock.unlock();}}private Thread thread;private Lock lock;private volatile boolean running = true;private class RealThread implements Runnable{public void run() {while (running) { // (1)lock.lock(); // (3)try {// do some real works...System.out.println("Thread is running...");} finally {lock.unlock();}}}}}
The above code works normally in most cases, but the deadlock still exists. A deadlock occurs when the thread is executed in the following sequence:
<1> the realthread thread is executed at (1), that is, when the while (running) is executed, it is preemptible by the deadthread.
<2> the deadthread thread calls the stop () function, and the thread points to the realthread thread in <1>. When the stop () function is executed at (2, will wait until the end of realthread, discard the CPU
<3> the realthread thread resumes execution. Because the deadthread occupies the lock, the realthread waits for the deadthread to release the lock at (3 ).
After <3> execution, the deadthread thread and the realthread thread wait for each other to cause a deadlock.