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

1

0

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()

Uniplanar answered 1/3, 2022 at 12:2 Comment(2)
Why? You want it to behave differently while being debugged? This way madness lies.Saltwater
@user207421: well... here's folie à deux, LOL.Meter
F
1

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.

Fitzgerald answered 7/3, 2022 at 1:15 Comment(1)
It is also worth noting that dumping and iterating the threads is relatively expensive. So you probably don't want the overhead of doing that every time you need to set a timeout on a future. Especially since most of the time you are not debugging your application.Diocesan

© 2022 - 2024 — McMap. All rights reserved.