OnJava8-Examples/threads/CaptureUncaughtException.java

61 lines
1.7 KiB
Java
Raw Normal View History

2016-07-05 14:46:09 -06:00
// threads/CaptureUncaughtException.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
2016-07-07 15:12:55 -06:00
import onjava.TimedAbort;
2015-06-15 17:47:35 -07:00
class ExceptionThread2 implements Runnable {
@Override
public void run() {
Thread t = Thread.currentThread();
2016-07-05 14:46:09 -06:00
System.out.println("run() by " + t.getName());
2015-06-15 17:47:35 -07:00
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e);
}
}
class HandlerThreadFactory implements ThreadFactory {
@Override
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) {
2016-07-07 15:12:55 -06:00
new TimedAbort(4);
2015-06-15 17:47:35 -07:00
ExecutorService exec = Executors.newCachedThreadPool(
new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2016-07-22 14:45:35 -06:00
HandlerThreadFactory@14991ad creating new Thread
2015-12-15 11:47:04 -08:00
created Thread[Thread-1,5,main]
2016-07-22 14:45:35 -06:00
eh = MyUncaughtExceptionHandler@d93b30
run() by Thread-1
eh = MyUncaughtExceptionHandler@d93b30
HandlerThreadFactory@14991ad creating new Thread
created Thread[Thread-2,5,main]
eh = MyUncaughtExceptionHandler@28e402
2015-06-15 17:47:35 -07:00
caught java.lang.RuntimeException
2016-07-22 14:45:35 -06:00
TimedAbort 4
2015-09-07 11:44:36 -06:00
*/