OnJava8-Examples/concurrency/CaptureUncaughtException.java

52 lines
1.4 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: concurrency/CaptureUncaughtException.java
2015-05-05 11:20:13 -07:00
// {TimeOutDuringTesting}
2015-04-20 15:36:01 -07:00
import java.util.concurrent.*;
class ExceptionThread2 implements Runnable {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void run() {
Thread t = Thread.currentThread();
System.out.println("run() by " + t);
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e);
}
}
class HandlerThreadFactory implements ThreadFactory {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public Thread newThread(Runnable r) {
System.out.println(this + " creating new Thread");
Thread t = new Thread(r);
System.out.println("created " + t);
t.setUncaughtExceptionHandler(
new MyUncaughtExceptionHandler());
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
return t;
}
}
public class CaptureUncaughtException {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool(
new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
} /* Output: (90% match)
HandlerThreadFactory@de6ced creating new Thread
created Thread[Thread-0,5,main]
eh = MyUncaughtExceptionHandler@1fb8ee3
run() by Thread[Thread-0,5,main]
eh = MyUncaughtExceptionHandler@1fb8ee3
caught java.lang.RuntimeException
2015-05-05 11:20:13 -07:00
*///:~