/** * 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"); }
/** * 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"); }
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);
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; } }
/* 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(); }
@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"); } }
@After public void after() throws InterruptedException { executor.shutdownNow(); if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { System.out.println("Warning: not all tasks completed promptly"); } }
/** 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(); } }
ExecutorService taskExecutor = Executors.newFixedThreadPool(4); while(...) { taskExecutor.execute(new MyTask()); } taskExecutor.shutdown(); try { taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { ... }
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); } }
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 } }
/** * 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); } }
@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); }
@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);
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)
private void shutdownAndAwaitTermination(ExecutorService pool) { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { pool.shutdownNow(); } } catch (InterruptedException e) { logger.warn("InstanceInfoReplicator stop interrupted"); } }
@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. } } }));
@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; }
@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"); }