Tried detecting the a self created DeadLock

2274 views java

I wrote the below Java code for creating the Deadlock, I passed a resource String variable to the threads and locked it using synchronized block and put up an infinite loop inside that so that first thread will never ever leave it, so the second thread will not be able to access it forever.

public class MainClass {

    public static void main(String[] args) {
        String resourcs = "testResource";
        MainClass M = new MainClass();
        Thread firstThread = new Thread( MyThread("First",resourcs));
        Thread seconThread =  new Thread( MyThread("Second",resourcs));


    class MyThread implements Runnable{
        String resource;
        String name;
        public MyThread(String name,String resource) {
            this.resource = resource;
   = name;

        public void run() {
            synchronized (resource) {
                while(true) {
                    try {
                    } catch (InterruptedException e) {
                    System.out.println("Still working on the thread :"+name);



Then in the other window, I wrote the code for detecting the Deadlock like below,


public class DetectDeadLock {
    public static void main(String args[]) {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean();
        long[] threadIds = bean.findDeadlockedThreads();

        if (threadIds != null) {
            ThreadInfo[] infos = bean.getThreadInfo(threadIds);

            for (ThreadInfo info : infos) {
                StackTraceElement[] stack = info.getStackTrace();
                // Log or store stack trace information.


But the Watch Dog detected nothing.

  1. Have I created the dead lock correctly? (I think yes, because the console is only printing the first thread's code)
  2. Do i have to wait for some time(idk how much) for the 'Watch Dog' code to detect the Deadlock?

answered question

This is not a Deadlock-situation because the first Thread can work totally fine. You need to create a situation where the second Thread waits for a resource of the first Thread and the first Thread waits for a resource of the second Thread.

1 Answer


There is no deadlock in your code. Deadlock happens when two threads wait for each other. This is not the case here. One thread waits, the other is active (in an endless loop, but that doesn't mean it's deadlocked.)

posted this

Have an answer?


Please login first before posting an answer.