Java Code Examples for java.util.concurrent.ThreadPoolExecutor#shutdown()
The following examples show how to use
java.util.concurrent.ThreadPoolExecutor#shutdown() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TunnelServerTest.java From tunnel with Apache License 2.0 | 6 votes |
@Test public void test_threadPool() { int total = 4; ThreadPoolExecutor executor = new ThreadPoolExecutor(total, total, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100)); for (int i = 0; i < total; i++) { executor.submit(new Task(i)); } try { executor.awaitTermination(1, TimeUnit.SECONDS); } catch (Exception e) { // } stopped = true; executor.shutdown(); }
Example 2
Source File: ScheduledExecutorTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * isTerminated is false before termination, true after */ public void testIsTerminated() throws InterruptedException { final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); assertFalse(p.isTerminated()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { assertFalse(p.isTerminated()); threadStarted.countDown(); await(done); }}); await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); try { p.shutdown(); } catch (SecurityException ok) { return; } assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); assertTrue(p.isTerminated()); } }
Example 3
Source File: MdwServletContainerFactory.java From mdw with Apache License 2.0 | 6 votes |
public void shutdownTomcatThreadpool() { connector.pause(); StandardLogger logger = LoggerUtil.getStandardLogger(); logger.info("Waiting for Tomcat threads to finish processing..."); int timeout = PropertyManager.getIntegerProperty(PropertyNames.MDW_THREADPOOL_TERMINATION_TIMEOUT, 30); Executor executor = this.connector.getProtocolHandler().getExecutor(); if (executor instanceof ThreadPoolExecutor) { try { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; threadPoolExecutor.shutdown(); if (!threadPoolExecutor.awaitTermination(timeout, TimeUnit.SECONDS)) { LoggerUtil.getStandardLogger().error("Thread pool fails to terminate after " + timeout + " seconds"); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } }
Example 4
Source File: ScheduledExecutorTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * isTerminated is false before termination, true after */ public void testIsTerminated() throws InterruptedException { final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); assertFalse(p.isTerminated()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { assertFalse(p.isTerminated()); threadStarted.countDown(); await(done); }}); await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); try { p.shutdown(); } catch (SecurityException ok) { return; } assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); assertTrue(p.isTerminated()); } }
Example 5
Source File: ScheduledExecutorSubclassTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * isTerminating is not true when running or when terminated */ public void testIsTerminating() throws InterruptedException { final CountDownLatch done = new CountDownLatch(1); final ThreadPoolExecutor p = new CustomExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { final CountDownLatch threadStarted = new CountDownLatch(1); assertFalse(p.isTerminating()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { assertFalse(p.isTerminating()); threadStarted.countDown(); await(done); }}); await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); try { p.shutdown(); } catch (SecurityException ok) { return; } assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); assertTrue(p.isTerminated()); assertFalse(p.isTerminating()); } }
Example 6
Source File: ThreadPoolExecutorDemo.java From JavaGuide with Apache License 2.0 | 6 votes |
public static void main(String[] args) { //使用阿里巴巴推荐的创建线程池的方式 //通过ThreadPoolExecutor构造函数自定义参数创建 ThreadPoolExecutor executor = new ThreadPoolExecutor( CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<>(QUEUE_CAPACITY), new ThreadPoolExecutor.CallerRunsPolicy()); for (int i = 0; i < 10; i++) { //创建WorkerThread对象(WorkerThread类实现了Runnable 接口) Runnable worker = new MyRunnable("" + i); //执行Runnable executor.execute(worker); } //终止线程池 executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("Finished all threads"); }
Example 7
Source File: ThreadPoolBuilderTest.java From vjtools with Apache License 2.0 | 6 votes |
@Test public void scheduledPool() { ScheduledThreadPoolExecutor singlePool = ThreadPoolBuilder.scheduledPool().build(); assertThat(singlePool.getCorePoolSize()).isEqualTo(1); assertThat(singlePool.getMaximumPoolSize()).isEqualTo(Integer.MAX_VALUE); singlePool.shutdown(); ScheduledThreadPoolExecutor sizeablePool = ThreadPoolBuilder.scheduledPool().setPoolSize(2).build(); assertThat(sizeablePool.getCorePoolSize()).isEqualTo(2); assertThat(sizeablePool.getMaximumPoolSize()).isEqualTo(Integer.MAX_VALUE); sizeablePool.shutdown(); ThreadPoolExecutor fixPoolWithNamePrefix = ThreadPoolBuilder.scheduledPool() .setThreadNamePrefix("scheduledPool").build(); Thread thread = fixPoolWithNamePrefix.getThreadFactory().newThread(new Runnable() { @Override public void run() { } }); assertThat(thread.getName()).startsWith("scheduledPool"); fixPoolWithNamePrefix.shutdown(); }
Example 8
Source File: ThreadPoolExecutorTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * isTerminated is false before termination, true after */ public void testIsTerminated() throws InterruptedException { final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10)); try (PoolCleaner cleaner = cleaner(p)) { final CountDownLatch threadStarted = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); assertFalse(p.isTerminating()); p.execute(new CheckedRunnable() { public void realRun() throws InterruptedException { assertFalse(p.isTerminating()); threadStarted.countDown(); await(done); }}); await(threadStarted); assertFalse(p.isTerminating()); done.countDown(); try { p.shutdown(); } catch (SecurityException ok) { return; } assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); assertTrue(p.isTerminated()); assertFalse(p.isTerminating()); } }
Example 9
Source File: ThreadUtil.java From datawave with Apache License 2.0 | 5 votes |
/** * Shuts down the executor and gives tasks that are still in progress the given amount of time before continuing. * * @param executor * @param timeToWait * @param unit * @return true if all tasks completed, false, if we interrupted and continued. */ public static boolean shutdownAndWait(ThreadPoolExecutor executor, long timeToWait, TimeUnit unit) { executor.shutdown(); try { executor.awaitTermination(timeToWait, unit); return true; } catch (InterruptedException e) { logger.warn("Closed thread pool but not all threads completed successfully."); return false; } }
Example 10
Source File: AbstractQueueVisitorTest.java From bazel with Apache License 2.0 | 5 votes |
@Test public void callerOwnedPool() throws Exception { ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); assertThat(executor.getActiveCount()).isSameInstanceAs(0); CountingQueueVisitor counter = new CountingQueueVisitor(executor); counter.enqueue(); counter.awaitQuiescence(/*interruptWorkers=*/ false); assertThat(counter.getCount()).isSameInstanceAs(10); executor.shutdown(); assertThat(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS)) .isTrue(); }
Example 11
Source File: RshServerTestThreaded.java From p4ic4idea with Apache License 2.0 | 5 votes |
/** * Test 'rsh' mode server. */ @Test public void testRshServer() { try{ ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); //adjust number of threads as needed for testing for (int i = 1; i <= 2; i++) { String depotPath = "//depot/..."; SyncDepot task = new SyncDepot(depotPath); System.out.println("A new task has been added to sync : " + depotPath); executor.execute(task); } executor.shutdown(); while (!executor.isTerminated()) { System.out.println("Threads are still running..."); Thread.sleep(1000); } System.out.println("Finished all threads"); } catch (Exception exc) { fail("Unexpected exception: " + exc.getLocalizedMessage()); } }
Example 12
Source File: ConcurrentEngineUsageTest.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
@Deployment public void testConcurrentUsage() throws Exception { if(!processEngineConfiguration.getDatabaseType().equals("h2") && !processEngineConfiguration.getDatabaseType().equals("db2")) { int numberOfThreads = 5; int numberOfProcessesPerThread = 5; int totalNumberOfTasks = 2 * numberOfThreads * numberOfProcessesPerThread; ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(numberOfThreads)); for(int i=0; i< numberOfThreads; i++) { executor.execute(new ConcurrentProcessRunnerRunnable(numberOfProcessesPerThread, "kermit" + i)); } // Wait for termination or timeout and check if all tasks are complete executor.shutdown(); boolean isEnded = executor.awaitTermination(20000, TimeUnit.MILLISECONDS); if(!isEnded) { log.error("Executor was not shut down after timeout, not al tasks have been executed"); executor.shutdownNow(); } assertEquals(0, executor.getActiveCount()); // Check there are no processes active anymore assertEquals(0, runtimeService.createProcessInstanceQuery().count()); if(processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) { // Check if all processes and tasks are complete assertEquals(numberOfProcessesPerThread * numberOfThreads, historyService.createHistoricProcessInstanceQuery() .finished().count()); assertEquals(totalNumberOfTasks, historyService.createHistoricTaskInstanceQuery() .finished().count()); } } }
Example 13
Source File: AbstractQueueVisitorTest.java From bazel with Apache License 2.0 | 5 votes |
@Test public void interruptionWithInterruptingWorkers() throws Exception { assertInterruptWorkers(null); ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); assertInterruptWorkers(executor); executor.shutdown(); executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); }
Example 14
Source File: DefaultTimerThreadPoolAdapter.java From tomee with Apache License 2.0 | 5 votes |
private void doShutdownExecutor(final boolean waitJobs) { final ThreadPoolExecutor tpe = (ThreadPoolExecutor) executor; tpe.shutdown(); if (waitJobs) { final int timeout = SystemInstance.get().getOptions().get(OPENEJB_EJB_TIMER_POOL_AWAIT_SECONDS, 5); try { tpe.awaitTermination(timeout, TimeUnit.SECONDS); } catch (final InterruptedException e) { logger.error(e.getMessage(), e); } } }
Example 15
Source File: JmsConnection.java From qpid-jms with Apache License 2.0 | 5 votes |
protected JmsConnection(final JmsConnectionInfo connectionInfo, Provider provider) throws JMSException { // This executor can be used for dispatching asynchronous tasks that might block or result // in reentrant calls to this Connection that could block. The thread in this executor // will also serve as a means of preventing JVM shutdown should a client application // not have it's own mechanism for doing so if the configuration specifies that the // Connection create this thread as a non-daemon thread. executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new QpidJMSThreadFactory("QpidJMS Connection Executor: " + connectionInfo.getId(), connectionInfo.isUseDaemonThread())); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); // We need to start the core thread in order for it to prevent JVM shutdown as our // single non-daemon thread. executor.execute(new Runnable() { @Override public void run() { } }); this.provider = provider; this.provider.setProviderListener(this); try { this.provider.start(); } catch (Exception e) { executor.shutdown(); throw JmsExceptionSupport.create(e); } this.connectionInfo = connectionInfo; this.connectionInfo.setConnection(this); }
Example 16
Source File: GracefulShutdown.java From modeldb with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ContextClosedEvent event) { this.connector.pause(); Executor executor = this.connector.getProtocolHandler().getExecutor(); if (executor instanceof ThreadPoolExecutor) { try { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; int nfsActiveRequestCount = threadPoolExecutor.getActiveCount(); while (nfsActiveRequestCount > 0) { nfsActiveRequestCount = threadPoolExecutor.getActiveCount(); System.err.println("NFS Active Request Count in while: " + nfsActiveRequestCount); try { Thread.sleep(1000); // wait for 1s } catch (InterruptedException e) { e.printStackTrace(); } } threadPoolExecutor.shutdown(); if (!threadPoolExecutor.awaitTermination(shutdownTimeout, TimeUnit.SECONDS)) { System.err.println( "NFS Server thread pool did not shut down gracefully within " + shutdownTimeout + " seconds. Proceeding with forceful shutdown"); threadPoolExecutor.shutdownNow(); if (!threadPoolExecutor.awaitTermination(shutdownTimeout, TimeUnit.SECONDS)) { System.err.println("NFS Server thread pool did not terminate"); } } else { System.err.println("*** NFS Server Shutdown ***"); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } }
Example 17
Source File: NetUtil.java From JavaWeb with Apache License 2.0 | 5 votes |
@Deprecated public static Map<String,Boolean> pingIpForInetAddress(List<Callable<Boolean>> list,ThreadPoolExecutor threadPoolExecutor) throws Exception { Map<String,Boolean> map = new LinkedHashMap<>(); CompletionService<Boolean> completionService = new ExecutorCompletionService<>(threadPoolExecutor); for(int i=0;i<list.size();i++){ completionService.submit(list.get(i)); } for(int i=0;i<list.size();i++){ IpCallForInetAddress ipCall = (IpCallForInetAddress)list.get(i); map.put(ipCall.getIpAddress(),completionService.take().get()); } threadPoolExecutor.shutdown(); return map; }
Example 18
Source File: ConnectChannelHandlerTest.java From dubbo-2.6.5 with Apache License 2.0 | 5 votes |
@Test(expected = ExecutionException.class) public void test_Connect_Execute_Error() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHander(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "connectionExecutor", 1); executor.shutdown(); handler.connected(new MockedChannel()); }
Example 19
Source File: HttpBulkNodeClientTest.java From elasticsearch-helper with Apache License 2.0 | 4 votes |
@Test public void testThreadedRandomDocs() throws Exception { int maxthreads = Runtime.getRuntime().availableProcessors(); long maxactions = MAX_ACTIONS; final long maxloop = NUM_ACTIONS; logger.info("HttpBulkNodeClient max={} maxactions={} maxloop={}", maxthreads, maxactions, maxloop); final HttpBulkNodeClient client = ClientBuilder.builder() .put("host", "127.0.0.1") .put("port", 9200) .put(ClientBuilder.MAX_ACTIONS_PER_REQUEST, maxactions) .put(ClientBuilder.FLUSH_INTERVAL, TimeValue.timeValueSeconds(60)) .setMetric(new LongAdderIngestMetric()) .toHttpBulkNodeClient(); try { client.newIndex("test") .startBulk("test", -1, 1000); ThreadPoolExecutor pool = EsExecutors.newFixed("http-bulk-nodeclient-test", maxthreads, 30, EsExecutors.daemonThreadFactory("http-bulk-nodeclient-test")); final CountDownLatch latch = new CountDownLatch(maxthreads); for (int i = 0; i < maxthreads; i++) { pool.execute(new Runnable() { public void run() { for (int i = 0; i < maxloop; i++) { client.index("test", "test", null, "{ \"name\" : \"" + randomString(32) + "\"}"); } latch.countDown(); } }); } logger.info("waiting for max 30 seconds..."); latch.await(30, TimeUnit.SECONDS); logger.info("flush..."); client.flushIngest(); client.waitForResponses(TimeValue.timeValueSeconds(30)); logger.info("got all responses, thread pool shutdown..."); pool.shutdown(); logger.info("pool is shut down"); } catch (NoNodeAvailableException e) { logger.warn("skipping, no node available"); } finally { client.stopBulk("test"); assertEquals(maxthreads * maxloop, client.getMetric().getSucceeded().getCount()); if (client.hasThrowable()) { logger.error("error", client.getThrowable()); } assertFalse(client.hasThrowable()); client.refreshIndex("test"); SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(client.client(), SearchAction.INSTANCE) .setQuery(QueryBuilders.matchAllQuery()).setSize(0); assertEquals(maxthreads * maxloop, searchRequestBuilder.execute().actionGet().getHits().getTotalHits()); client.shutdown(); } }
Example 20
Source File: QueueingThreadPoolExecutorTest.java From openhab-core with Eclipse Public License 2.0 | 4 votes |
/** * Test basic thread creation, including thread settings (name, prio, * daemon). */ protected void basicTestPoolSize2ThreadSettings(String poolName) throws InterruptedException { ThreadPoolExecutor pool = QueueingThreadPoolExecutor.createInstance(poolName, 2); // pool 2 tasks, threads must exist pool.execute(createRunnable10s()); assertEquals(pool.getActiveCount(), 1); assertTrue(isPoolThreadActive(poolName, 1)); Thread t1 = getThread(poolName + "-1"); assertEquals(t1.isDaemon(), false); // thread will be NORM prio or max prio of this thread group, which can // < than NORM int prio1 = Math.min(t1.getThreadGroup().getMaxPriority(), Thread.NORM_PRIORITY); assertEquals(t1.getPriority(), prio1); pool.execute(createRunnable10s()); assertEquals(pool.getActiveCount(), 2); assertTrue(isPoolThreadActive(poolName, 2)); Thread t2 = getThread(poolName + "-2"); assertEquals(t2.isDaemon(), false); // thread will be NORM prio or max prio of this thread group, which can // < than NORM int prio2 = Math.min(t2.getThreadGroup().getMaxPriority(), Thread.NORM_PRIORITY); assertEquals(t2.getPriority(), prio2); // 2 more tasks, will be queued, no threads pool.execute(createRunnable1s()); // as pool size is 2, no more active threads, will stay at 2 assertEquals(pool.getActiveCount(), 2); assertFalse(isPoolThreadActive(poolName, 3)); assertEquals(pool.getQueue().size(), 1); pool.execute(createRunnable1s()); assertEquals(pool.getActiveCount(), 2); assertFalse(isPoolThreadActive(poolName, 4)); assertEquals(pool.getQueue().size(), 2); // 0 are yet executed assertEquals(pool.getCompletedTaskCount(), 0); // needs to wait CORE_POOL_TIMEOUT + 2sec-queue-thread + x until all // threads are down again pool.shutdown(); Thread.sleep(CORE_POOL_TIMEOUT + 3000); assertFalse(areThreadsFromPoolRunning(poolName)); }