Tried detecting the a self created DeadLock

2274 views java
6

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(M.new MyThread("First",resourcs));
        Thread seconThread =  new Thread(M.new MyThread("Second",resourcs));
        firstThread.start();
        seconThread.start();

    }

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

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

                }
            }
        }

    }
}

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

import java.lang.management.ManagementFactory; 
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

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();
                System.out.println("here");
                // 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

9

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?

JD

Please login first before posting an answer.