Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
final class PoolService {
  private static final ThreadFactory factory = new
    ExceptionThreadFactory(new MyExceptionHandler());
  private static final ExecutorService pool =
    Executors.newFixedThreadPool(10, factory);

  public void doSomething() {	   
    pool.execute(new Task()); // Task is a runnable class	      	    	      
  }
 
  public static class ExceptionThreadFactory implements ThreadFactory  {			
    private static final ThreadFactory defaultFactory =
      Executors.defaultThreadFactory();
    private final Thread.UncaughtExceptionHandler handler;

    public ExceptionThreadFactory(Thread.UncaughtExceptionHandler handler) {
      this.handler = handler;
    }

    @Override public Thread newThread(Runnable run) {
      Thread thread = defaultFactory.newThread(run);
      thread.setUncaughtExceptionHandler(handler);
      return thread;
    }
  }
	  
  public static class MyExceptionHandler extends ExceptionReporter 
    implements Thread.UncaughtExceptionHandler {

    private final Logger logger = Logger.getLogger("com.organization.Log");
    // ... 

    @Override public void uncaughtException(Thread thread, Throwable t) {
      logger.log(Level.SEVERE, "Thread exited with exception: " + thread.getName(), t);	// Recovery or logging code		      
    }
  }	  
}

Wiki Markup
Note that the uncaught exception handler is not called if the method {{ExecutorService.submit()}} is invoked. This is because the thrown exception is considered to be part of the return status and is consequently, re-thrown by {{Future.get()}}, wrapped in an {{ExecutionException}} \[[Goetz 06|AA. Java References#Goetz 06]\]. 

...