Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: not done yet...

...

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 {
    // ... 

    @Override public void uncaughtException(Thread thread, Throwable t) {
      // Recovery or logging code		      
    }
  }	  
}

Wiki Markup
The {{ExecutorService.submit()}} method can be used to submit a task to a thread pool instead of the {{execute()}} method to obtain a {{Future}} object.  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, wrapped in an {{ExecutionException}} and re-thrown by {{Future.get()}}, wrapped in an {{ExecutionException}} \[[Goetz 06|AA. Java References#Goetz 06]\]. 

...