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

How to use
awaitTermination
method
in
java.util.concurrent.ExecutorService

Best Java code snippets using java.util.concurrent.ExecutorService.awaitTermination (Showing top 20 results out of 15,570)

Refine searchRefine arrow

  • ExecutorService.shutdown
  • Executors.newFixedThreadPool
  • ExecutorService.shutdownNow
  • ExecutorService.submit
  • PrintStream.println
  • ExecutorService.execute
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: iluwatar/java-design-patterns

/**
 * Stops the reactor and related resources such as dispatcher.
 * 
 * @throws InterruptedException
 *           if interrupted while stopping the reactor.
 * @throws IOException
 *           if any I/O error occurs.
 */
public void stop() throws InterruptedException, IOException {
 reactorMain.shutdownNow();
 selector.wakeup();
 reactorMain.awaitTermination(4, TimeUnit.SECONDS);
 selector.close();
 LOGGER.info("Reactor stopped");
}
origin: stackoverflow.com

 final ExecutorService producers = Executors.newFixedThreadPool(100);
final ExecutorService consumers = Executors.newFixedThreadPool(100);
while (/* has more work */) {
 producers.submit(...);
}
producers.shutdown();
producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
consumers.shutdown();
consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
origin: iBotPeaches/Apktool

public static String execAndReturn(String[] cmd) {
  ExecutorService executor = Executors.newCachedThreadPool();
  try {
    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectErrorStream(true);
    Process process = builder.start();
    StreamCollector collector = new StreamCollector(process.getInputStream());
    executor.execute(collector);
    process.waitFor();
    if (! executor.awaitTermination(15, TimeUnit.SECONDS)) {
      executor.shutdownNow();
      if (! executor.awaitTermination(5, TimeUnit.SECONDS)) {
        System.err.println("Stream collector did not terminate.");
      }
    }
    return collector.get();
  } catch (IOException | InterruptedException e) {
    return null;
  }
}
origin: stackoverflow.com

 /* Get an executor service that will run a maximum of 5 threads at a time: */
ExecutorService exec = Executors.newFixedThreadPool(5);
/* For all the 100 tasks to be done altogether... */
for (int i = 0; i < 100; i++) {
  /* ...execute the task to run concurrently as a runnable: */
  exec.execute(new Runnable() {
    public void run() {
      /* do the work to be done in its own thread */
      System.out.println("Running in: " + Thread.currentThread());
    }
  });
}
/* Tell the executor that after these 100 steps above, we will be done: */
exec.shutdown();
try {
  /* The tasks are now running concurrently. We wait until all work is done, 
   * with a timeout of 50 seconds: */
  boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);
  /* If the execution timed out, false is returned: */
  System.out.println("All done: " + b);
} catch (InterruptedException e) { e.printStackTrace(); }
origin: PipelineAI/pipeline

@AfterClass
public static void tearDown() {
  threadPool.shutdown();
  try {
    threadPool.awaitTermination(10, TimeUnit.SECONDS);
  } catch (InterruptedException ie) {
    System.out.println("Thread pool never terminated in HystrixRollingPercentileTest");
  }
}
origin: real-logic/aeron

@After
public void after() throws InterruptedException
{
  executor.shutdownNow();
  if (!executor.awaitTermination(5, TimeUnit.SECONDS))
  {
    System.out.println("Warning: not all tasks completed promptly");
  }
}
origin: objectbox/objectbox-java

/** dump thread stacks if pool does not terminate promptly. */
private void checkThreadTermination() {
  try {
    if (!threadPool.awaitTermination(1, TimeUnit.SECONDS)) {
      int activeCount = Thread.activeCount();
      System.err.println("Thread pool not terminated in time; printing stack traces...");
      Thread[] threads = new Thread[activeCount + 2];
      int count = Thread.enumerate(threads);
      for (int i = 0; i < count; i++) {
        System.err.println("Thread: " + threads[i].getName());
        Thread.dumpStack();
      }
    }
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
}
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: robolectric/robolectric

private static void shutdownDbExecutor(ExecutorService executorService, Collection<SQLiteConnection> connections) {
 for (final SQLiteConnection connection : connections) {
  getFuture("close connection on reset", executorService.submit(new Callable<Void>() {
   @Override
   public Void call() throws Exception {
    connection.dispose();
    return null;
   }
  }));
 }
 executorService.shutdown();
 try {
  executorService.awaitTermination(30, TimeUnit.SECONDS);
 } catch (InterruptedException e) {
  throw new RuntimeException(e);
 }
}
origin: LeonardoZ/java-concurrency-patterns

  public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newCachedThreadPool();
    // Synchronized - Vector
    Vector<Long> vec = new Vector<>();

    Runnable insertIfAbsent = () -> {
      long millis = System.currentTimeMillis() / 1000;
      insertIfAbsent(vec, millis);
    };
    for (int i = 0; i < 10001; i++) {
      executor.execute(insertIfAbsent);
    }
    executor.shutdown();
    executor.awaitTermination(4000, TimeUnit.SECONDS);

    // Using the wrappers for not sync collections
    // List<String> synchronizedList = Collections.synchronizedList(abcList);
    // Collections.synchronizedMap(m)
    // Collections.synchronizedXXX
  }
}
origin: GlowstoneMC/Glowstone

/**
 * Downloads the libraries.
 */
public void run() {
  if (!directory.isDirectory() && !directory.mkdirs()) {
    GlowServer.logger
        .log(Level.SEVERE, "Could not create libraries directory: " + directory);
  }
  for (Library library : libraries) {
    downloaderService.execute(new LibraryDownloader(library));
  }
  downloaderService.shutdown();
  try {
    if (!downloaderService.awaitTermination(1, TimeUnit.MINUTES)) {
      downloaderService.shutdownNow();
    }
  } catch (InterruptedException e) {
    GlowServer.logger.log(Level.SEVERE, "Library Manager thread interrupted: ", e);
  }
}
origin: SonarSource/sonarqube

@Test
public void two_concurrent_calls_to_startit_call_migration_engine_only_once() throws Exception {
 pool.submit(new CallStartit());
 pool.submit(new CallStartit());
 pool.awaitTermination(2, TimeUnit.SECONDS);
 assertThat(triggerCount.get()).isEqualTo(1);
}
origin: ReactiveX/RxJava

@Test(timeout = 30000)
public void testIssue2890NoStackoverflow() throws InterruptedException {
  final ExecutorService executor = Executors.newFixedThreadPool(2);
  final Scheduler sch = Schedulers.from(executor);
  executor.awaitTermination(20000, TimeUnit.MILLISECONDS);
origin: stackoverflow.com

 ExecutorService pool = Executors.newFixedThreadPool(10);
for (String name : fileNames) {
  pool.submit(new DownloadTask(name, toPath));
}
pool.shutdown();
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// all tasks have now finished (unless an exception is thrown above)
origin: Netflix/eureka

private void shutdownAndAwaitTermination(ExecutorService pool) {
  pool.shutdown();
  try {
    if (!pool.awaitTermination(3, TimeUnit.SECONDS)) {
      pool.shutdownNow();
    }
  } catch (InterruptedException e) {
    logger.warn("InstanceInfoReplicator stop interrupted");
  }
}
origin: google/guava

 @Override
 public void run() {
  try {
   // We'd like to log progress and failures that may arise in the
   // following code, but unfortunately the behavior of logging
   // is undefined in shutdown hooks.
   // This is because the logging code installs a shutdown hook of its
   // own. See Cleaner class inside {@link LogManager}.
   service.shutdown();
   service.awaitTermination(terminationTimeout, timeUnit);
  } catch (InterruptedException ignored) {
   // We're shutting down anyway, so just ignore.
  }
 }
}));
origin: codingapi/tx-lcn

@Bean
public ExecutorService executorService() {
  ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    executorService.shutdown();
    try {
      executorService.awaitTermination(10, TimeUnit.MINUTES);
    } catch (InterruptedException ignored) {
    }
  }));
  return executorService;
}
origin: Graylog2/graylog2-server

@Override
protected void shutDown() throws Exception {
  LOG.debug("Stopping BufferSynchronizerService");
  if (cluster.isConnected() && cluster.isDeflectorHealthy()) {
    final ExecutorService executorService = executorService(metricRegistry);
    executorService.submit(new Runnable() {
      @Override
      public void run() {
        bufferSynchronizer.waitForEmptyBuffers(configuration.getShutdownTimeout(), TimeUnit.MILLISECONDS);
      }
    });
    executorService.shutdown();
    executorService.awaitTermination(configuration.getShutdownTimeout(), TimeUnit.MILLISECONDS);
  } else {
    LOG.warn("Elasticsearch is unavailable. Not waiting to clear buffers and caches, as we have no healthy cluster.");
  }
  LOG.debug("Stopped BufferSynchronizerService");
}
java.util.concurrentExecutorServiceawaitTermination

Javadoc

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Popular methods of ExecutorService

  • 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
  • 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
  • getSharedPreferences (Context)
  • onCreateOptionsMenu (Activity)
  • scheduleAtFixedRate (ScheduledExecutorService)
  • Scanner (java.util)
    A parser that parses a text string of primitive types and strings with the help of regular expressio
  • ThreadPoolExecutor (java.util.concurrent)
    An ExecutorService that executes each submitted task using one of possibly several pooled threads, n
  • JLabel (javax.swing)
  • JList (javax.swing)
  • Scheduler (org.quartz)
    This is the main interface of a Quartz Scheduler. A Scheduler maintains a registry of org.quartz.Job
  • LoggerFactory (org.slf4j)
    The LoggerFactory is a utility class producing Loggers for various logging APIs, most notably for lo
  • From CI to AI: The AI layer in your organization
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