How to programmatically detect whether current JVM is connected by a remote debugger?

347 views Asked by At

The situation that I'm facing is when I debug my code in a sub-thread, whose wrapping future has a timeout, I always get a TimeoutException on the outter future.get(timeout), my idea is if I can know that a debugger is connected, I can dynamically enlarge the timeout parameter of the future.get()

1

There are 1 answers

1
apangin On

One option to find if debugger is attached is to check whether a thread named "JDWP Command Reader" is running:

public static boolean isDebuggerPresent() {
    ThreadInfo[] infos = ((com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean())
            .dumpAllThreads(false, false, 0);
    for (ThreadInfo info : infos) {
        if ("JDWP Command Reader".equals(info.getThreadName())) {
            return true;
        }
    }
    return false;
}

However, I'd suggest against detecting debugger programmatically. In general, application behavior should never depend on the presence of debugger, otherwise it ruins the entire idea of debugging the real application. It's probably better to make timeout explicitly configurable from outside.