Skip to content

Instantly share code, notes, and snippets.

@aozturk
Last active November 19, 2015 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aozturk/f46866f8b6936b4b415e to your computer and use it in GitHub Desktop.
Save aozturk/f46866f8b6936b4b415e to your computer and use it in GitHub Desktop.
class MyThreadFactory implements ThreadFactory {
private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
private final Thread.UncaughtExceptionHandler handler;
public MyThreadFactory(Thread.UncaughtExceptionHandler handler) {
this.handler = handler;
}
@Override
public Thread newThread(Runnable run) {
Thread thread = defaultFactory.newThread(run);
thread.setUncaughtExceptionHandler(handler);
return thread;
}
}
class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread thread, Throwable t) {
System.err.println("Uncaught exception is detected! " + t
+ " st: " + Arrays.toString(t.getStackTrace()));
// ... Handle the exception
}
}
final class MyTask implements Runnable {
@Override
public void run() {
System.out.println("My task is started running...");
// ...
throw new ArithmeticException();
// ...
}
}
public class UncaughtExceptionHandler {
public static void main(String[] args) {
ThreadFactory factory = new MyThreadFactory(new MyExceptionHandler());
ExecutorService threadPool = Executors.newFixedThreadPool(10, factory);
threadPool.execute(new MyTask());
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment