1

I am wondering if I invoke findDeadlockedThreads periodly inside JVM, there are performance issues at pos <1> or <2> below because of JVM STW(Stop of The World)?

ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] threadIds = bean.findDeadlockedThreads(); // <1>

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

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

I check some posts e.g. Which method is the least obtrusive for generating thread dumps in java?. It looks like "JMX from inside the JVM" is a heavy operation.

So my Questions are:

  1. Will ThreadMXBean operations such as "findDeadlockedThreads" or "getThreadInfo" cause JVM STW?
  2. Does it make sense if I periodly invoke ThreadMXBean "findDeadlockedThreads" or "getThreadInfo" inside a normal Java process which running business?

updated:

I made a demo for question 1 and found "findDeadlockedThreads" caused STW and "getStackTrace" did not. I added jvm option "-XX:+PrintGCApplicationStoppedTime" to verify the STW event and scheduled a time task to invoke "findDeadlockedThreads" and "getStackTrace". Does it make sense?

findDeadlockedThreads demo:

static class DeadLockCheckTask extends TimerTask {
        @Override
        public void run() {
            ThreadMXBean bean = ManagementFactory.getThreadMXBean();
            long[] threadIds = bean.findDeadlockedThreads(); // <1>
            System.out.println("dead lock checker task running...");
            if (threadIds != null) {
                ThreadInfo[] infos = bean.getThreadInfo(threadIds); // <2>

                for (ThreadInfo info : infos) {
                    StackTraceElement[] stack = info.getStackTrace();
                    // Log or store stack trace information.
                    for(StackTraceElement e : stack) {
                        System.out.println("threadName:" + info.getThreadName() + "-----" + e.toString());
                    }
                }
            }
        }
    }

enter image description here

getStackTrace demo:

    static class ThreadDumpTask extends TimerTask {

        @Override
        public void run() {
            System.out.println("thread dump task running...");
            for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
                System.out.println(ste + "\n");
            }
        }
    }

enter image description here

Stone
  • 155
  • 1
  • 6

0 Answers0