I suspect you need
private volatile Throwable throwable
You tried to use ExecutorService as it is built in and does it for you. The following prints
future1 := result future2 threw java.lang.IllegalStateException future3 timed out
Code
public static void main(String... args) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future1 = executor.submit(new Callable<String>() { public String call() throws Exception { return "result"; } }); Future<String> future2 = executor.submit(new Callable<String>() { public String call() throws Exception { throw new IllegalStateException(); } }); Future<String> future3 = executor.submit(new Callable<String>() { public String call() throws Exception { Thread.sleep(2000); throw new AssertionError(); } }); printResult("future1", future1); printResult("future2", future2); printResult("future3", future3); executor.shutdown(); } private static void printResult(String description, Future<String> future) { try { System.out.println(description+" := "+future.get(1, TimeUnit.SECONDS)); } catch (InterruptedException e) { System.out.println(description+" interrupted"); } catch (ExecutionException e) { System.out.println(description+" threw "+e.getCause()); } catch (TimeoutException e) { System.out.println(description+" timed out"); } }
There is a comment in the code for FutureTask.
If you are not going to reuse the code in the JDK, you should still read it so that you can use any tricks that they use.
source share