Last active
November 19, 2015 14:31
-
-
Save aozturk/f46866f8b6936b4b415e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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