@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(); } }
@Override public boolean isDisposed() { Future<?> f = get(); return f == null || f.isDone(); }
@Override public boolean isCancelled() { lock.lock(); try { return currentFuture.isCancelled(); } finally { lock.unlock(); } }
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 CountDownLatch latch = new CountDownLatch(1); ExecutorService service = Executors.newFixedThreadPool(threadCount); List<Future<Throwable>> workers = new ArrayList<>(threadCount); boolean needShutdown = true; for (int i = 0; i != threadCount; ++i) { final int index = i; workers.add(service.submit(new Callable<Throwable>() { @Override public Throwable call() { latch.countDown(); service.shutdown(); assertTrue(service.awaitTermination(10, TimeUnit.SECONDS)); needShutdown = false; for (Future<Throwable> callable : workers) { assertTrue("If this failure happen frequently, we can try to increase the wait time", callable.isDone()); assertNull("Sensor#checkQuotas SHOULD be thread-safe!", callable.get());
@Test( timeout = 5_000 ) public void shouldStopAndWaitForAllJobsToFinish() throws Throwable { // Given when( config.jobLimit() ).thenReturn( 2 ); JobScheduler jobScheduler = createInitialisedScheduler(); final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker( config, jobScheduler ); final CountDownLatch latch1 = new CountDownLatch( 1 ); final CountDownLatch latch2 = new CountDownLatch( 1 ); WaitingIndexSamplingJob job1 = new WaitingIndexSamplingJob( indexId11, latch1 ); WaitingIndexSamplingJob job2 = new WaitingIndexSamplingJob( indexId22, latch1 ); jobTracker.scheduleSamplingJob( job1 ); jobTracker.scheduleSamplingJob( job2 ); Future<?> stopping = Executors.newSingleThreadExecutor().submit( () -> { latch2.countDown(); jobTracker.stopAndAwaitAllJobs(); } ); // When latch2.await(); assertFalse( stopping.isDone() ); latch1.countDown(); stopping.get( 10, SECONDS ); // Then assertTrue( stopping.isDone() ); assertNull( stopping.get() ); assertTrue( job1.executed ); assertTrue( job2.executed ); }
ExecutorService es = Executors.newFixedThreadPool(CONCURRENCY); maxIterations, idAuthority, ids); uids.add(idAuthority.getUniqueID()); futures.add(es.submit(stressRunnable)); f.get(); } catch (ExecutionException e) { throw e.getCause(); es.shutdownNow();
final ExecutorService pool = Executors.newFixedThreadPool(2); final CompletionService<String> service = new ExecutorCompletionService<String>(pool); final List<? extends Callable<String>> callables = Arrays.asList( new SleepingCallable("slow", 5000), new SleepingCallable("quick", 500)); for (final Callable<String> callable : callables) { service.submit(callable); } pool.shutdown(); try { while (!pool.isTerminated()) { final Future<String> future = service.take(); System.out.println(future.get()); } } catch (ExecutionException | InterruptedException ex) { }
private void tailResponse(final String method, final Response response, final ProgressHandler handler, final WebTarget resource) throws DockerException, InterruptedException { final ExecutorService executor = Executors.newSingleThreadExecutor(); try { final ProgressStream stream = response.readEntity(ProgressStream.class); final Future<?> future = executor.submit( new ResponseTailReader(stream, handler, method, resource)); future.get(); } catch (ExecutionException e) { final Throwable cause = e.getCause(); if (cause instanceof DockerException) { throw (DockerException)cause; } else { throw new DockerException(cause); } } finally { executor.shutdownNow(); try { response.close(); } catch (ProcessingException e) { // ignore, thrown by jnr-unixsocket when httpcomponent try to read after close // the socket is closed before this exception } } }
@Test public void isnt_inheritable() throws Exception { ExecutorService service = Executors.newCachedThreadPool(); try (Scope scope = currentTraceContext.newScope(context)) { assertThat(service.submit(() -> { verifyImplicitContext(null); return currentTraceContext.get(); }).get()).isNull(); } catch (ExecutionException e) { if (e.getCause() instanceof Error) throw (Error) e.getCause(); throw (Exception) e.getCause(); } assertThat(service.submit(currentTraceContext::get).get()) .isNull(); verifyImplicitContext(null); service.shutdownNow(); }
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 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(); }
@Test public void testMultipleClients() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); try { ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<>(exec); for (int i = 0; i < NUM_THREADS; ++i) ecs.submit(new IdLockTestThread("client_" + i)); for (int i = 0; i < NUM_THREADS; ++i) { Future<Boolean> result = ecs.take(); assertTrue(result.get()); } idLock.assertMapEmpty(); } finally { exec.shutdown(); exec.awaitTermination(5000, TimeUnit.MILLISECONDS); } }
configuration.getClass(StressTestUtils.STRESSOR_CLASS, StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class); ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads); ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(), new SharedLimiterKey(resourceLimited)); ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor(); reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS); futures.add(executorService.submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter), stressor))); for (Future<?> future : futures) { try { future.get(); } catch (ExecutionException ee) { stressorFailures++; executorService.shutdownNow();
ExecutorService service1 = Executors.newSingleThreadExecutor(); ScheduledExecutorService service2 = null; try { Future f = service1.submit(() -> { final ExcerptAppender appender = queue.acquireAppender(); service2 = Executors.newSingleThreadScheduledExecutor(); service2.scheduleAtFixedRate(() -> { Bytes b = Bytes.elasticHeapByteBuffer(128); final ExcerptTailer tailer = queue.createTailer(); if (bytes == null) { f.get(1, TimeUnit.SECONDS); throw new NullPointerException("nothing in result"); f.get(1, TimeUnit.SECONDS); } finally { bytes.release(); service1.shutdownNow(); if (service2 != null) service2.shutdownNow();
@Test public void testLockRetentionDuringFailover() throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(1); Future<?> putFuture = executorService.submit(() -> cache.put(1L, "one")); clusterControl.terminateActive(); clusterControl.waitForActive(); assertThat(loaderWriter.backingMap.isEmpty(), is(true)); latch.countDown(); putFuture.get(); assertThat(loaderWriter.backingMap.get(1L), is("one")); }
private void execute( List<RecordStresser> recordStressers ) throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newFixedThreadPool( numberOfThreads, r -> { Thread thread = Executors.defaultThreadFactory().newThread( r ); thread.setDaemon( true ); return thread; } ); List<Future<Void>> futures = executorService.invokeAll( recordStressers ); for ( Future<Void> future : futures ) { future.get(); } executorService.shutdown(); assertTrue( executorService.awaitTermination( 10, TimeUnit.SECONDS ) ); }
@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); } }
@Override public void runUninterruptiblyWithTimeout( Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit) throws TimeoutException { checkNotNull(runnable); checkNotNull(timeoutUnit); checkPositiveTimeout(timeoutDuration); Future<?> future = executor.submit(runnable); try { Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit); } catch (TimeoutException e) { future.cancel(true /* mayInterruptIfRunning */); throw e; } catch (ExecutionException e) { wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause()); throw new AssertionError(); } }
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); final Future handler = executor.submit(new Callable(){ ... }); executor.schedule(new Runnable(){ public void run(){ handler.cancel(); } }, 10000, TimeUnit.MILLISECONDS);