Concurrency deadlock Medium

Improper use of locks in a multi-threaded program can lead to deadlock and cause the program to be unresponsive. A deadlock can occur when two distinct threads try to acquire two locks in reverse order.

Detector ID
java/concurrency-deadlock@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1public class ConcurrencyDeadlockNoncompliant {
2
3    Object syncObject1 = new Object();
4    Object syncObject2 = new Object();
5
6    // Noncompliant: both methods request the same two locks in the opposite order, which can cause deadlock.
7
8    public void noncompliantsync1() {
9        synchronized (syncObject1) {
10            synchronized (syncObject2) {
11                System.out.println("Deadlock noncompliant example.");
12                // Placeholder for code.
13            }
14        }
15    }
16
17    public void noncompliantsync2() {
18        synchronized (syncObject2) {
19            synchronized (syncObject1) {
20                System.out.println("Deadlock noncompliant example.");
21                // Placeholder for code.
22            }
23        }
24    }
25}

Compliant example

1public class ConcurrencyDeadlockCompliant {
2
3    Object syncObject1 = new Object();
4    Object syncObject2 = new Object();
5
6    // Compliant: both methods request the two locks in the same order.
7
8    public void compliantsync1() {
9        synchronized (syncObject1) {
10            synchronized (syncObject2) {
11                System.out.println("Deadlock compliant example.");
12                // Placeholder for code.
13            }
14        }
15    }
16
17    public void compliantsync2() {
18        synchronized (syncObject1) {
19            synchronized (syncObject2) {
20                System.out.println("Deadlock compliant example.");
21                // Placeholder for code.
22            }
23        }
24    }
25}