This is an alternative way to do this. Hint from here
package com.autonomy.introspect.service; import java.sql.SQLException; import java.util.concurrent.*; public class MyExecutor extends ThreadPoolExecutor { public static void main(String[] args) { MyExecutor threadPool = new MyExecutor(); Task<Object> task = new Task<Object>(); Future<Object> futureTask = threadPool.submit(task); try { System.out.println(futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { System.out.println("exception thrown: " + e.getMessage()); } } public MyExecutor() { super(4, 20, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(4000)); } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); System.out.println("in afterExecute()"); if (t != null) { System.out.println("exception thrown: " + t.getMessage()); } else { System.out.println("t == null"); } } private static class Task<V> implements Callable<V> { @Override public V call() throws Exception { System.out.println("in call()"); throw new SQLException("testing.."); } } }
Using afterExecute for another purpose.
This class provides protected overridable beforeExecute(java.lang.Thread, java.lang.Runnable) and afterExecute(java.lang.Runnable, java.lang.Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated. If hook or callback methods throw exceptions, internal worker threads may
in turn fails and abruptly stops.
Tyagi Akhilesh
source share