Posts How to create deadlock using static final variables
Post
Cancel

How to create deadlock using static final variables

Watch Explanation on YouTube

How to create deadlock using static final variables in java

Link URL : https://youtu.be/p0HNCppq80A

Code

If you run the below code, public static void main method, the code execution will result in a deadlock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class Singleton {
    public static final int TIMEOUT = getValue();

    private static int getValue() {
        return 10;
    }

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
        synchronized (this) {
            Thread thread = Thread.currentThread();
            while (thread.isAlive()) {
                try {
                    wait(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Singleton instance() {
        return INSTANCE;
    }

    @Override
    public String toString() {
        return "Singleton{}";
    }
}

class SomeClass {
    public static void main(String[] args) {
        new Thread(() -> System.out.println("the timeout value is " + Singleton.TIMEOUT)).start();

        new Thread(() -> System.out.println("instance received " + Singleton.instance())).start();
    }
}
This post is licensed under CC BY 4.0 by the author.