Tabnine Logo
ExecutorService
Code IndexAdd Tabnine to your IDE (free)

How to use
ExecutorService
in
java.util.concurrent

Best Java code snippets using java.util.concurrent.ExecutorService (Showing top 20 results out of 59,247)

Refine searchRefine arrow

  • Executors
  • Future
  • ExecutionException
  • CountDownLatch
  • Executor
  • AtomicInteger
canonical example by Tabnine

public void runThreadTask() {
 ExecutorService service = Executors.newCachedThreadPool();
 service.execute(
   () -> {
    // ... do something inside runnable task
   });
 service.shutdown();
}
origin: google/guava

@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();
 }
}
origin: stackoverflow.com

 ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
 taskExecutor.execute(new MyTask());
}
taskExecutor.shutdown();
try {
 taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
 ...
}
origin: square/okhttp

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();
}
origin: iluwatar/java-design-patterns

 /**
  * 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);
 }
}
origin: iluwatar/java-design-patterns

/**
 * 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");
}
origin: apache/hive

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();
 }
}
origin: ReactiveX/RxJava

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();
origin: spring-projects/spring-framework

@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();
}
origin: google/guava

@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();
 }
}
origin: ReactiveX/RxJava

@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();
  }
}
origin: pentaho/pentaho-kettle

@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 );
}
origin: google/guava

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);
origin: google/guava

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();
origin: ReactiveX/RxJava

@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());
origin: google/guava

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();
 }
}
origin: google/guava

@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());
}
origin: google/guava

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) {
origin: square/dagger

@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);
 }
}
origin: apache/kafka

@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);
  }
}
java.util.concurrentExecutorService

Javadoc

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The #shutdownmethod will allow previously submitted tasks to execute before terminating, while the #shutdownNow method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

Method submit extends base method Executor#execute by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

Usage Examples

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors#newFixedThreadPool factory method:
  
class NetworkService implements Runnable public void run() { // run the service 
try  
for (;;)  
pool.execute(new Handler(serverSocket.accept())); 
} 
} catch (IOException ex)  
pool.shutdown(); 
} 
} 
} 
class Handler implements Runnable  
private final Socket socket; 
Handler(Socket socket) { this.socket = socket; } 
public void run()  
// read and service request on socket 
} 
}}
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:
  
void shutdownAndAwaitTermination(ExecutorService pool) } catch (InterruptedException ie)  
// (Re-)Cancel if current thread also interrupted 
pool.shutdownNow(); 
// Preserve interrupt status 
Thread.currentThread().interrupt(); 
} 
}}

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorServicehappen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

Most used methods

  • submit
    Submits a value-returning task for execution and returns a Future representing the pending results o
  • shutdown
    Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks wil
  • execute
  • shutdownNow
    Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a
  • awaitTermination
    Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or
  • isShutdown
    Returns true if this executor has been shut down.
  • isTerminated
    Returns true if all tasks have completed following shut down. Note that isTerminated is never true
  • invokeAll
    Executes the given tasks, returning a list of Futures holding their status and results when all comp
  • invokeAny
    Executes the given tasks, returning the result of one that has completed successfully (i.e., without
  • <init>

Popular in Java

  • Making http post requests using okhttp
  • putExtra (Intent)
  • notifyDataSetChanged (ArrayAdapter)
  • findViewById (Activity)
  • ConnectException (java.net)
    A ConnectException is thrown if a connection cannot be established to a remote host on a specific po
  • Time (java.sql)
    Java representation of an SQL TIME value. Provides utilities to format and parse the time's represen
  • Hashtable (java.util)
    A plug-in replacement for JDK1.5 java.util.Hashtable. This version is based on org.cliffc.high_scale
  • List (java.util)
    An ordered collection (also known as a sequence). The user of this interface has precise control ove
  • UUID (java.util)
    UUID is an immutable representation of a 128-bit universally unique identifier (UUID). There are mul
  • DataSource (javax.sql)
    An interface for the creation of Connection objects which represent a connection to a database. This
  • CodeWhisperer alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now