@Test(expected = CancellationException.class, timeout = 1000L) public void testWaitCancel() throws ExecutionException, InterruptedException { Executor executor = Executors.newSingleThreadExecutor(); TestListener<Integer> listener = new TestListener<Integer>(); final ListenableFutureTask<Integer> future = new ListenableFutureTask<Integer>( new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(1000000); return 0; } }); future.addListener(listener); executor.execute(future); new Thread( new Runnable() { @Override public void run() { future.cancel(true); } }) .start(); try { future.get(); Assert.fail("get() succeeded"); } finally { Assert.assertTrue(listener.waitValue() instanceof CancellationException); } }
@Test(timeout = 1000L) public void testWaitSuccess() throws ExecutionException, InterruptedException { Executor executor = Executors.newSingleThreadExecutor(); TestListener<Integer> listener = new TestListener<Integer>(); ListenableFutureTask<Integer> future = new ListenableFutureTask<Integer>( new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(1); return 1; } }); future.addListener(listener); executor.execute(future); Assert.assertEquals(1, (int) future.get()); Assert.assertEquals(1, (int) (Integer) listener.waitValue()); }
@Test(expected = ExecutionException.class, timeout = 1000L) public void testWaitFailure() throws ExecutionException, InterruptedException { Executor executor = Executors.newSingleThreadExecutor(); TestListener<Integer> listener = new TestListener<Integer>(); ListenableFutureTask<Integer> future = new ListenableFutureTask<Integer>( new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(1); throw new TestingRuntimeException(); } }); future.addListener(listener); executor.execute(future); try { future.get(); Assert.fail("get() succeeded"); } finally { Assert.assertTrue(listener.waitValue() instanceof TestingRuntimeException); } }