FutureUtils { public static <T> CompletableFuture<T> toCompletableFuture(ApiFuture<T> apiFuture) { CompletableFuture<T> completableFuture = new CompletableFuture<T>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { boolean result = apiFuture.cancel(mayInterruptIfRunning); super.cancel(mayInterruptIfRunning); return result; } }; ApiFutureCallback<T> callback = new ApiFutureCallback<T>() { public void onFailure(Throwable throwable) { completableFuture.completeExceptionally(throwable); } public void onSuccess(T t) { completableFuture.complete(t); } }; ApiFutures.addCallback(apiFuture, callback, MoreExecutors.directExecutor()); return completableFuture; }  static CompletableFuture<T> toCompletableFuture(ApiFuture<T> apiFuture); static CompletableFuture<T> toCompletableFuture(ListenableFuture<T> listenableFuture); static CompletableFuture<T> failedFuture(Throwable error); static final ExecutorService DIRECT_EXECUTOR; }
@Test public void testToCompletableFuture() throws Exception { String result = "Result"; ListeningExecutorService service = MoreExecutors.listeningDecorator( BigtableSessionSharedThreadPools.getInstance().getBatchThreadPool()); ListenableFuture<String> listenableFuture = service.submit( new Callable<String>() { public String call() throws Exception { Thread.sleep(1000); return result; } }); CompletableFuture<String> completableFuture = FutureUtils.toCompletableFuture(listenableFuture); assertFalse("Should be in progress", completableFuture.isDone()); Throwable t = null; try { completableFuture.get(500, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { t = e; } assertNotNull("TimeoutException is expected", t); assertEquals(result, completableFuture.get()); }
@Test public void testToCompletableFuture_exception() throws Exception { ListeningExecutorService service = MoreExecutors.listeningDecorator( BigtableSessionSharedThreadPools.getInstance().getBatchThreadPool()); ListenableFuture<String> listenableFuture = service.submit( new Callable<String>() { public String call() throws Exception { throw new IllegalStateException("Test failed feature"); } }); CompletableFuture<String> completableFuture = FutureUtils.toCompletableFuture(listenableFuture); thrown.expect(ExecutionException.class); thrown.expectCause(IsInstanceOf.<Throwable>instanceOf(IllegalStateException.class)); thrown.expectMessage(containsString("Test failed feature")); completableFuture.get(); }