为什么对未绘图异常的处理似乎发生在异常行为发生的死线程中

  • 本文关键字:异常 线程 处理 绘图 java multithreading
  • 更新时间 :
  • 英文 :


我借用了另一个问题:

@Slf4j
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread() {
public void run() {
try {
//do some stuff
LOG.debug("about to throw a RE from a worker thead");
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("purposeful!");
}
};
LOG.debug("in main thead");
t.setUncaughtExceptionHandler(
(thread, throwable) -> LOG.debug("in main thread; catching exception from worker. uncaught exception from worker thread: {} from {}",
throwable.getMessage(), thread.getName()));
t.start();
TimeUnit.SECONDS.sleep(10);
LOG.debug("done-main thead");
}
}

如果运行,将产生以下输出:

10:19:50.249 [main] DEBUG com.foo.services.search.Main - in main thead
10:19:50.258 [Thread-0] DEBUG com.foo.services.search.Main - about to throw a RE from a worker thead
10:19:50.258 [Thread-0] DEBUG com.foo.services.search.Main - in main thread; catching exception from worker. uncaught exception from worker thread: purposeful! from Thread-0
10:20:00.258 [main] DEBUG com.foo.services.search.Main - done-main thead

为什么,当线程0完成时,可丢弃的捕获活动似乎发生在这个完成的线程内?

JDK的doc中指出,此方法仅由JVM调用:

/**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}

出于好奇,我找到了热点的相关源代码:https://github.com/openjdk/jdk/blob/master/src/hotspot/share/runtime/thread.cpp

正如您在thread.cpp中看到的,当thread退出时,会触发此逻辑:

// For any new cleanup additions, please check to see if they need to be applied to
// cleanup_failed_attach_current_thread as well.
void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
// ........
if (!destroy_vm) {
if (uncaught_exception.not_null()) {
EXCEPTION_MARK;
// Call method Thread.dispatchUncaughtException().
Klass* thread_klass = vmClasses::Thread_klass();
//...
}

最新更新