canonical example by Tabnine
public void runThreadTask() { ExecutorService service = Executors.newCachedThreadPool(); service.execute( () -> { // ... do something inside runnable task }); service.shutdown(); }
@Override public void runWithTimeout(Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit) throws TimeoutException, InterruptedException { checkNotNull(runnable); checkNotNull(timeoutUnit); checkPositiveTimeout(timeoutDuration); Future<?> future = executor.submit(runnable); try { future.get(timeoutDuration, timeoutUnit); } catch (InterruptedException | TimeoutException e) { future.cancel(true /* mayInterruptIfRunning */); throw e; } catch (ExecutionException e) { wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause()); throw new AssertionError(); } }
ExecutorService taskExecutor = Executors.newFixedThreadPool(4); while(...) { taskExecutor.execute(new MyTask()); } taskExecutor.shutdown(); try { taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { ... }
private void parallelDrainQueue(int threadCount) { ExecutorService executor = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { executor.execute(new NamedRunnable("Crawler %s", i) { @Override protected void execute() { try { drainQueue(); } catch (Exception e) { e.printStackTrace(); } } }); } executor.shutdown(); }
/** * Stops the pool of workers. * * @throws InterruptedException if interrupted while stopping pool of workers. */ @Override public void stop() throws InterruptedException { executorService.shutdown(); executorService.awaitTermination(4, TimeUnit.SECONDS); } }
/** * Stops logging clients. This is a blocking call. */ public void stop() { service.shutdown(); if (!service.isTerminated()) { service.shutdownNow(); try { service.awaitTermination(1000, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.error("exception awaiting termination", e); } } LOGGER.info("Logging clients stopped"); }
private void runParallelQueries(String[] queries) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(queries.length); final CountDownLatch cdlIn = new CountDownLatch(queries.length), cdlOut = new CountDownLatch(1); Future<?>[] tasks = new Future[queries.length]; for (int i = 0; i < tasks.length; ++i) { tasks[i] = executor.submit(new QueryRunnable(hiveConf, queries[i], cdlIn, cdlOut)); } cdlIn.await(); // Wait for all threads to be ready. cdlOut.countDown(); // Release them at the same time. for (int i = 0; i < tasks.length; ++i) { tasks[i].get(); } }
final int NUM_RETRIES = Flowable.bufferSize() * 2; int ncpu = Runtime.getRuntime().availableProcessors(); ExecutorService exec = Executors.newFixedThreadPool(Math.max(ncpu / 2, 2)); try { for (int r = 0; r < NUM_LOOPS; r++) { final AtomicInteger timeouts = new AtomicInteger(); final Map<Integer, List<String>> data = new ConcurrentHashMap<Integer, List<String>>(); final CountDownLatch cdl = new CountDownLatch(m); for (int i = 0; i < m; i++) { final int j = i; exec.execute(new Runnable() { @Override public void run() { cdl.await(); assertEquals(0, timeouts.get()); if (data.size() > 0) { fail("Data content mismatch: " + allSequenceFrequency(data)); exec.shutdown();
@Test public void nonSharedEngine() throws Exception { int iterations = 20; this.view.setEngineName("nashorn"); this.view.setRenderFunction("render"); this.view.setSharedEngine(false); this.view.setApplicationContext(this.context); ExecutorService executor = Executors.newFixedThreadPool(4); List<Future<Boolean>> results = new ArrayList<>(); for (int i = 0; i < iterations; i++) { results.add(executor.submit(() -> view.getEngine() != null)); } assertEquals(iterations, results.size()); for (int i = 0; i < iterations; i++) { assertTrue(results.get(i).get()); } executor.shutdown(); }
@GwtIncompatible // Threads public void testTransformAsync_functionToString() throws Exception { final CountDownLatch functionCalled = new CountDownLatch(1); final CountDownLatch functionBlocking = new CountDownLatch(1); AsyncFunction<Object, Object> function = new AsyncFunction<Object, Object>() { @Override public ListenableFuture<Object> apply(Object input) throws Exception { functionCalled.countDown(); functionBlocking.await(); return immediateFuture(null); } @Override public String toString() { return "Called my toString"; } }; ExecutorService executor = Executors.newSingleThreadExecutor(); try { ListenableFuture<?> output = Futures.transformAsync(immediateFuture(null), function, executor); functionCalled.await(); assertThat(output.toString()).contains("Called my toString"); } finally { functionBlocking.countDown(); executor.shutdown(); } }
@Test public void disposeRace() { ExecutorService exec = Executors.newSingleThreadExecutor(); final Scheduler s = Schedulers.from(exec, true); try { for (int i = 0; i < 500; i++) { final Worker w = s.createWorker(); final AtomicInteger c = new AtomicInteger(2); w.schedule(new Runnable() { @Override public void run() { c.decrementAndGet(); while (c.get() != 0) { } } }); c.decrementAndGet(); while (c.get() != 0) { } w.dispose(); } } finally { exec.shutdownNow(); } }
@Test public void concurrentSyslogMessageTest() throws Exception { SyslogMessageTask syslogMessage = null; ExecutorService service = Executors.newFixedThreadPool( numOfTasks ); for ( int i = 0; i < numOfTasks; i++ ) { syslogMessage = createSyslogMessageTask(); service.execute( syslogMessage ); } service.shutdown(); countDownLatch.countDown(); service.awaitTermination( 10000, TimeUnit.NANOSECONDS ); Assert.assertTrue( numOfErrors.get() == 0 ); }
int tasksPerThread = 10; int nTasks = nThreads * tasksPerThread; ExecutorService pool = Executors.newFixedThreadPool(nThreads); ImmutableList<String> keys = ImmutableList.of("a", "b", "c"); try { List<Future<int[]>> futures = Lists.newArrayListWithExpectedSize(nTasks); for (int i = 0; i < nTasks; i++) { futures.add(pool.submit(new MutateTask(multiset, keys))); int[] taskDeltas = future.get(); for (int i = 0; i < deltas.length; i++) { deltas[i] += taskDeltas[i]; assertEquals("Counts not as expected", Ints.asList(deltas), actualCounts); } finally { pool.shutdownNow(); assertTrue("map should not contain a zero", value.get() != 0);
final ExecutorService executor = Executors.newFixedThreadPool(numThreads); for (int i = 0; i < 1000; i++) { final AtomicInteger counter = new AtomicInteger(); final TrustedListenableFutureTask<Integer> task = TrustedListenableFutureTask.create( executor.execute(wrapper); assertEquals(1, counter.get()); executor.shutdown();
@Test(timeout = 30000) public void testIssue2890NoStackoverflow() throws InterruptedException { final ExecutorService executor = Executors.newFixedThreadPool(2); final Scheduler sch = Schedulers.from(executor); final AtomicInteger counter = new AtomicInteger(); executor.awaitTermination(20000, TimeUnit.MILLISECONDS); assertEquals(n, counter.get());
public void testEnqueueAndDispatch_multithreaded() throws InterruptedException { Object listener = new Object(); ExecutorService service = Executors.newFixedThreadPool(4); ListenerCallQueue<Object> queue = new ListenerCallQueue<>(); try { queue.addListener(listener, service); final CountDownLatch latch = new CountDownLatch(1); Multiset<Object> counters = ConcurrentHashMultiset.create(); queue.enqueue(incrementingEvent(counters, listener, 1)); queue.enqueue(incrementingEvent(counters, listener, 2)); queue.enqueue(incrementingEvent(counters, listener, 3)); queue.enqueue(incrementingEvent(counters, listener, 4)); queue.enqueue(countDownEvent(latch)); assertEquals(0, counters.size()); queue.dispatch(); latch.await(); assertEquals(multiset(listener, 4), counters); } finally { service.shutdown(); } }
@GwtIncompatible // threads public void testSubmitAsync_asyncCallable_cancelledBeforeApplyingFunction() throws InterruptedException { final AtomicBoolean callableCalled = new AtomicBoolean(); AsyncCallable<Integer> callable = new AsyncCallable<Integer>() { @Override public ListenableFuture<Integer> call() { callableCalled.set(true); return immediateFuture(1); } }; ExecutorService executor = newSingleThreadExecutor(); // Pause the executor. final CountDownLatch beforeFunction = new CountDownLatch(1); executor.execute( new Runnable() { @Override public void run() { awaitUninterruptibly(beforeFunction); } }); ListenableFuture<Integer> future = submitAsync(callable, executor); future.cancel(false); // Unpause the executor. beforeFunction.countDown(); executor.shutdown(); assertTrue(executor.awaitTermination(5, SECONDS)); assertFalse(callableCalled.get()); }
public void testRejectedExecutionThrownWithMultipleCalls() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final SettableFuture<?> future = SettableFuture.create(); final Executor delegate = final ExecutorService blocked = Executors.newCachedThreadPool(); Future<?> first = blocked.submit( new Runnable() { @Override } catch (RejectedExecutionException expected) { latch.countDown(); try { first.get(10, TimeUnit.SECONDS); fail(); } catch (ExecutionException expected) {
@Test public void concurrentSingletonAccess() throws Exception { final List<Future<Long>> futures = new ArrayList<Future<Long>>(); final ObjectGraph graph = ObjectGraph.createWith(new TestingLoader(), new LatchingModule(latch)); for (int i = 0; i < THREAD_COUNT; i++) { futures.add(es.submit(new Callable<Long>() { @Override public Long call() { latch.countDown(); return graph.get(Long.class); } })); } latch.countDown(); for (Future<Long> future : futures) { assertThat(future.get(1, TimeUnit.SECONDS)) .named("Lock failure - count should never increment") .isEqualTo(0); } }
@Test public void testTimeoutAndRetryJoinGroupIfNeeded() throws Exception { setupCoordinator(); mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(mockTime.timer(0)); ExecutorService executor = Executors.newFixedThreadPool(1); try { Timer firstAttemptTimer = mockTime.timer(REQUEST_TIMEOUT_MS); Future<Boolean> firstAttempt = executor.submit(() -> coordinator.joinGroupIfNeeded(firstAttemptTimer)); mockTime.sleep(REQUEST_TIMEOUT_MS); assertFalse(firstAttempt.get()); assertTrue(consumerClient.hasPendingRequests(coordinatorNode)); mockClient.respond(joinGroupFollowerResponse(1, "memberId", "leaderId", Errors.NONE)); mockClient.prepareResponse(syncGroupResponse(Errors.NONE)); Timer secondAttemptTimer = mockTime.timer(REQUEST_TIMEOUT_MS); Future<Boolean> secondAttempt = executor.submit(() -> coordinator.joinGroupIfNeeded(secondAttemptTimer)); assertTrue(secondAttempt.get()); } finally { executor.shutdownNow(); executor.awaitTermination(1000, TimeUnit.MILLISECONDS); } }