protected void checkExceptionHandling( final LinkedBlockingQueue<Throwable> unexpectedExceptions, ExecutorTaskAgent agent, Future<?> future, Class<? extends Exception> expectedKlass, boolean isExpected) throws InterruptedException { try { future.get(); } catch (ExecutionException ce) { assertTrue(expectedKlass.isInstance(ce.getCause())); // ok } agent.awaitPendingTasks(); if (expectedKlass == null || isExpected) { assertTrue(unexpectedExceptions.size() == 0); return; } else { assertTrue(unexpectedExceptions.size() == 1); Throwable removed = unexpectedExceptions.remove(); assertTrue(expectedKlass.isInstance(removed)); } }
public void testExceptionHandling$() throws Exception { final LinkedBlockingQueue<Throwable> unexpectedExceptions = new LinkedBlockingQueue<>(); ExecutorTaskAgent agent = new ExecutorTaskAgent("testExceptionHandling") { @Override protected void handleUnexpectedException(Throwable throwable) { if (throwable != null) { unexpectedExceptions.add(throwable); } } }; Future<?> future; Runnable npeRunnable = new Runnable() { @Override public void run() { throw new RuntimeException(); // a RuntimeException, representing an internal error } }; Callable<String> normalTask = new Callable<String>() { @Override public String call() throws Exception { throw new IOException("Some expected exception"); } }; future = agent.submit(npeRunnable); try { future.cancel(true); future.get(); } catch (CancellationException ce) { // ok } agent.awaitPendingTasks(); assertTrue(unexpectedExceptions.size() == 0); checkExceptionHandling( unexpectedExceptions, agent, agent.submit(npeRunnable), RuntimeException.class, false); checkExceptionHandling( unexpectedExceptions, agent, agent.submit(normalTask), IOException.class, true); }