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

D Blacksmith
  • 123
  • 2
  • 6

1 Answers1

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
apangin
  • 92,924
  • 10
  • 193
  • 247
  • 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. – Stephen C Mar 07 '22 at 01:57