/** * Shorthand for {@link #runAsync(ThrowingRunnable, ExecutorService)} using {@link * ForkJoinPool#commonPool()}. */ public static CompletionStage<Void> runAsync(ThrowingRunnable runnable) { return runAsync(runnable, ForkJoinPool.commonPool()); }
private static void executeBatches(List<BatchRequest> batches) throws IOException { ExecutorService executor = MoreExecutors.listeningDecorator( new ThreadPoolExecutor( MAX_CONCURRENT_BATCHES, MAX_CONCURRENT_BATCHES, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>())); List<CompletionStage<Void>> futures = new ArrayList<>(); for (final BatchRequest batch : batches) { futures.add(MoreFutures.runAsync(() -> batch.execute(), executor)); } try { MoreFutures.get(MoreFutures.allAsList(futures)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while executing batch GCS request", e); } catch (ExecutionException e) { if (e.getCause() instanceof FileNotFoundException) { throw (FileNotFoundException) e.getCause(); } throw new IOException("Error executing batch GCS request", e); } finally { executor.shutdown(); } }
@Test public void runAsyncSuccess() throws Exception { AtomicInteger result = new AtomicInteger(0); CompletionStage<Void> sideEffectFuture = MoreFutures.runAsync( () -> { result.set(42); }); MoreFutures.get(sideEffectFuture); assertThat(result.get(), equalTo(42)); }
@Test public void runAsyncFailure() throws Exception { final String testMessage = "this is just a test"; CompletionStage<Void> sideEffectFuture = MoreFutures.runAsync( () -> { throw new IllegalStateException(testMessage); }); thrown.expect(ExecutionException.class); thrown.expectCause(isA(IllegalStateException.class)); thrown.expectMessage(testMessage); MoreFutures.get(sideEffectFuture); } }