Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is UncaughtExceptionHandler not called by ExecutorService?
    primarykey
    data
    text
    <p>I've stumbled upon a problem, that can be summarized as follows:</p> <p>When I create the thread manually (i.e. by instantiating <code>java.lang.Thread</code>) the <code>UncaughtExceptionHandler</code> is called appropriately. However, when I use an <code>ExecutorService</code> with a <code>ThreadFactory</code> the handler is ommited. What did I miss?</p> <pre><code>public class ThreadStudy { private static final int THREAD_POOL_SIZE = 1; public static void main(String[] args) { // create uncaught exception handler final UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { synchronized (this) { System.err.println("Uncaught exception in thread '" + t.getName() + "': " + e.getMessage()); } } }; // create thread factory ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { // System.out.println("creating pooled thread"); final Thread thread = new Thread(r); thread.setUncaughtExceptionHandler(exceptionHandler); return thread; } }; // create Threadpool ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE, threadFactory); // create Runnable Runnable runnable = new Runnable() { @Override public void run() { // System.out.println("A runnable runs..."); throw new RuntimeException("Error in Runnable"); } }; // create Callable Callable&lt;Integer&gt; callable = new Callable&lt;Integer&gt;() { @Override public Integer call() throws Exception { // System.out.println("A callable runs..."); throw new Exception("Error in Callable"); } }; // a) submitting Runnable to threadpool threadPool.submit(runnable); // b) submit Callable to threadpool threadPool.submit(callable); // c) create a thread for runnable manually final Thread thread_r = new Thread(runnable, "manually-created-thread"); thread_r.setUncaughtExceptionHandler(exceptionHandler); thread_r.start(); threadPool.shutdown(); System.out.println("Done."); } } </code></pre> <p>I expect: Three times the message "Uncaught exception..."</p> <p>I get: The message once (triggered by the manually created thread). </p> <p>Reproduced with Java 1.6 on Windows 7 and Mac OS X 10.5.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload