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) { }
public synchronized Future<Boolean> process() { if (future != null) { return future; } ExecutorService shutdownExecutor = Executors.newSingleThreadExecutor(); FutureTask<Boolean> task = new ShutdownTask(); shutdownExecutor.execute(task); shutdownExecutor.shutdown(); future = task; return future; }
ExecutorService es = Executors.newCachedThreadPool(); for(int i=0;i<5;i++) es.execute(new Runnable() { /* your task */ }); es.shutdown(); boolean finshed = es.awaitTermination(1, TimeUnit.MINUTES); // all tasks have finished or the time has been reached.
ExecutorService exec = Executors.newFixedThreadPool(4, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; } }); exec.execute(YourTaskNowWillBeDaemon);
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(expected = SSLHandshakeException.class) public void testClientRenegotiationFails() throws Throwable { int port = PortAssignment.unique(); ExecutorService workerPool = Executors.newCachedThreadPool(); final SSLServerSocket listeningSocket = x509Util.createSSLServerSocket(); SSLSocket clientSocket = null; SSLSocket serverSocket = null; final AtomicInteger handshakesCompleted = new AtomicInteger(0); try { InetSocketAddress localServerAddress = new InetSocketAddress( listeningSocket.bind(localServerAddress); Future<SSLSocket> acceptFuture; acceptFuture = workerPool.submit(new Callable<SSLSocket>() { @Override public SSLSocket call() throws Exception { serverSocket = acceptFuture.get(); } catch (ExecutionException e) { throw e.getCause(); forceClose(clientSocket); forceClose(listeningSocket); workerPool.shutdown(); Assert.assertEquals(1, handshakesCompleted.get());
@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 testInheritableThreadContextImmutability() throws Throwable { prepareThreadContext(true); try { newSingleThreadExecutor().submit(new Runnable() { @Override public void run() { testContextDataInjector(); } }).get(); } catch (ExecutionException ee) { throw ee.getCause(); } } }
@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 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(); }
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(); } }
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();
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();
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) {
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 scanSupportBuffered() throws InterruptedException { Executor plain = Runnable::run; ExecutorService plainService = Executors.newSingleThreadExecutor(); ExecutorService threadPool = Executors.newFixedThreadPool(3); ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4); .as("plainService").isEqualTo(null); scheduledThreadPool.schedule(() -> {}, 500, TimeUnit.MILLISECONDS); scheduledThreadPool.schedule(() -> {}, 500, TimeUnit.MILLISECONDS); Thread.sleep(50); //give some leeway for the pool to have consistent accounting .as("scheduledThreadPool").isEqualTo(2); threadPool.submit(() -> { try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } }); plainService.shutdownNow(); unsupportedScheduledExecutorService.shutdownNow(); threadPool.shutdownNow(); scheduledThreadPool.shutdownNow();