當前位置: 首頁>>代碼示例>>Java>>正文


Java ExecutorService.shutdownNow方法代碼示例

本文整理匯總了Java中java.util.concurrent.ExecutorService.shutdownNow方法的典型用法代碼示例。如果您正苦於以下問題:Java ExecutorService.shutdownNow方法的具體用法?Java ExecutorService.shutdownNow怎麽用?Java ExecutorService.shutdownNow使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.concurrent.ExecutorService的用法示例。


在下文中一共展示了ExecutorService.shutdownNow方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testCreateSessionDoesNotBlockWhenNotConfiguredTo

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
/**
 * Tests the behavior of the sessionPool of the PooledConnectionFactory when
 * maximum number of sessions are reached.
 *
 * @throws Exception
 */
@Test(timeout = 60000)
public void testCreateSessionDoesNotBlockWhenNotConfiguredTo() throws Exception {
    // using separate thread for testing so that we can interrupt the test
    // if the call to get a new session blocks.

    // start test runner thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    final Future<Boolean> result = executor.submit(new TestRunner());

    boolean testPassed = Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisfied() throws Exception {
            return result.isDone() && result.get().booleanValue();
        }
    }, TimeUnit.SECONDS.toMillis(10), TimeUnit.MILLISECONDS.toMillis(50));

    if (!testPassed) {
        PooledConnectionFactoryTest.LOG.error("2nd call to createSession() " +
                                              "is blocking but should have returned an error instead.");
        executor.shutdownNow();
        fail("SessionPool inside PooledConnectionFactory is blocking if " +
             "limit is exceeded but should return an exception instead.");
    }
}
 
開發者ID:messaginghub,項目名稱:pooled-jms,代碼行數:32,代碼來源:PooledConnectionTest.java

示例2: executorShutdown

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
private static void executorShutdown() {

        ExecutorService executor = Executors.newSingleThreadExecutor();
        try {
            System.out.println("shutdown executor");
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.err.println("tasks interrupted");
        } finally {
            if (!executor.isTerminated()) {
                System.err.println("cancel non-finished tasks");
            }
            executor.shutdownNow();
            System.out.println("shutdown finished");
        }
    }
 
開發者ID:daishicheng,項目名稱:outcomes,代碼行數:18,代碼來源:Main.java

示例3: joinPool

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
/**
 * Waits out termination of a thread pool or fails doing so.
 */
void joinPool(ExecutorService pool) {
    try {
        pool.shutdown();
        if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
            try {
                threadFail("ExecutorService " + pool +
                           " did not terminate in a timely manner");
            } finally {
                // last resort, for the benefit of subsequent tests
                pool.shutdownNow();
                pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
            }
        }
    } catch (SecurityException ok) {
        // Allowed in case test doesn't have privs
    } catch (InterruptedException fail) {
        threadFail("Unexpected InterruptedException");
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:JSR166TestCase.java

示例4: test

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
@Test
public void test() throws InterruptedException {
  AtomicInteger incrementor = new AtomicInteger();
  ResettableEvent are = new ResettableEvent(true);
  ResettableEvent done = new ResettableEvent(false);

  ExecutorService threadPool = Executors.newFixedThreadPool(3);
  for (int i = 0; i < 10; i++) {
    threadPool.submit(Interrupted.unchecked(() -> {
      are.getAndReset();
      incrementor.incrementAndGet();
      done.set();
    }));
  }

  done.getAndReset();
  Thread.sleep(100); // give a little time to other threads to increment, if there's indeed a bug
  assertEquals(1, incrementor.get());
  threadPool.shutdownNow();
}
 
開發者ID:linkedin,項目名稱:concurrentli,代碼行數:21,代碼來源:AutoResetEventTest.java

示例5: main

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
public static void main(String[] args) throws InterruptedException {
    TestSync testSync = new TestSync();

    ExecutorService es = Executors.newFixedThreadPool(200);
    int times = 1000000;

    for (int i = 0; i < times; i++) {
        es.submit(testSync::add);
        es.submit(TestSync::addStatic);
    }

    TimeUnit.SECONDS.sleep(1);
    es.shutdownNow();

    System.out.println("should be: " + times * 2 + ", actual is: " + testSync.getI());
}
 
開發者ID:firery,項目名稱:java-concurrency-cheatsheet,代碼行數:17,代碼來源:SyncMethods.java

示例6: verifyConcurrentServiceTicketGeneration

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
@Test
@IfProfileValue(name="cas.jpa.concurrent", value="true")
public void verifyConcurrentServiceTicketGeneration() throws Exception {
    final TicketGrantingTicket newTgt = newTGT();
    addTicketInTransaction(newTgt);
    final ExecutorService executor = Executors.newFixedThreadPool(CONCURRENT_SIZE);
    try {
        final List<ServiceTicketGenerator> generators = new ArrayList<>(CONCURRENT_SIZE);
        for (int i = 0; i < CONCURRENT_SIZE; i++) {
            generators.add(new ServiceTicketGenerator(newTgt.getId(), this.jpaTicketRegistry, this.txManager));
        }
        final List<Future<String>> results = executor.invokeAll(generators);
        for (final Future<String> result : results) {
            assertNotNull(result.get());
        }
    } catch (final Exception e) {
        logger.debug("testConcurrentServiceTicketGeneration produced an error", e);
        fail("testConcurrentServiceTicketGeneration failed.");
    } finally {
        executor.shutdownNow();
    }
}
 
開發者ID:hsj-xiaokang,項目名稱:springboot-shiro-cas-mybatis,代碼行數:23,代碼來源:JpaTicketRegistryTests.java

示例7: verifyConcurrentServiceTicketGeneration

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
@Test
public void verifyConcurrentServiceTicketGeneration() throws Exception {
    final TicketGrantingTicket newTgt = newTGT();
    addTicketInTransaction(newTgt);
    final ExecutorService executor = Executors.newFixedThreadPool(CONCURRENT_SIZE);
    try {
        final List<ServiceTicketGenerator> generators = new ArrayList<>(CONCURRENT_SIZE);
        for (int i = 0; i < CONCURRENT_SIZE; i++) {
            generators.add(new ServiceTicketGenerator(newTgt.getId(), this.ticketRegistry, this.txManager));
        }
        final List<Future<String>> results = executor.invokeAll(generators);
        for (final Future<String> result : results) {
            assertNotNull(result.get());
        }
    } catch (final Exception e) {
        LOGGER.error("testConcurrentServiceTicketGeneration produced an error", e);
        fail("testConcurrentServiceTicketGeneration failed.");
    } finally {
        executor.shutdownNow();
    }

    assertEquals(CONCURRENT_SIZE, this.ticketRegistry.getTickets().size() - 1);
}
 
開發者ID:mrluo735,項目名稱:cas-5.1.0,代碼行數:24,代碼來源:JpaTicketRegistryTests.java

示例8: generateUserAccountKey

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
public synchronized void generateUserAccountKey(User user) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {
    new RetryerHelper<User>(this).retry(5, TimeUnit.SECONDS, 30,
	    new AccountKeyCallableTask(user), IOException.class);
});
executorService.shutdown();
try {
    executorService.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
    log.error(e);
}
executorService.shutdownNow();
   }
 
開發者ID:ahmed-ebaid,項目名稱:invest-stash-rest,代碼行數:15,代碼來源:DBHelper.java

示例9: fillMemoryBlockMultiThreaded

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
private static void fillMemoryBlockMultiThreaded(final Instance instance) {

        ExecutorService service = Executors.newFixedThreadPool(instance.getLanes());
        List<Future<?>> futures = new ArrayList<Future<?>>();

        for (int i = 0; i < instance.getIterations(); i++) {
            for (int j = 0; j < ARGON2_SYNC_POINTS; j++) {
                for (int k = 0; k < instance.getLanes(); k++) {

                    final Position position = new Position(i, k, j, 0);

                    Future future = service.submit(new Runnable() {
                        @Override
                        public void run() {
                            FillSegment.fillSegment(instance, position);
                        }
                    });

                    futures.add(future);
                }

                joinThreads(instance, futures);
            }
        }

        service.shutdownNow();
    }
 
開發者ID:andreas1327250,項目名稱:argon2-java,代碼行數:28,代碼來源:FillMemory.java

示例10: main

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception
{
    int ponder = 5;
    if (args.length > 0)
    {
        ponder = Integer.parseInt(args[0]);
    }
    int size = 5;
    if (args.length > 1)
    {
        size = Integer.parseInt(args[1]);
    }
    ExecutorService exec = Executors.newCachedThreadPool();
    Chopstick[] sticks = new Chopstick[size];
    for (int i = 0; i < size; i++)
    {
        sticks[i] = new Chopstick();
    }
    for (int i = 0; i < size; i++)
    {
        exec.execute(new Philosopher(sticks[i], sticks[(i + 1) % size], i,
                ponder));
    }
    if (args.length == 3 && args[2].equals("timeout"))
    {
        TimeUnit.SECONDS.sleep(5);
    } else
    {
        System.out.println("Press 'Enter' to quit");
        System.in.read();
    }
    exec.shutdownNow();
}
 
開發者ID:baohongfei,項目名稱:think-in-java,代碼行數:34,代碼來源:DeadlockingDiningPhilosophers.java

示例11: stop

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
public static void stop(ExecutorService executor) {
    try {
        executor.shutdown();
        executor.awaitTermination(60, TimeUnit.SECONDS);
    }
    catch (InterruptedException e) {
        System.err.println("termination interrupted");
    }
    finally {
        if (!executor.isTerminated()) {
            System.err.println("killing non-finished tasks");
        }
        executor.shutdownNow();
    }
}
 
開發者ID:daishicheng,項目名稱:outcomes,代碼行數:16,代碼來源:ConcurrentUtils.java

示例12: cleanupExecutor

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
/**
 * Perform proper ThreadPool cleanup.
 */
private final void cleanupExecutor(ExecutorService executor)
{
    @SuppressWarnings("unused")
    List<Runnable> pending = executor.shutdownNow();
    // Can pending.size() be > 0?
}
 
開發者ID:adnanmitf09,項目名稱:Rubus,代碼行數:10,代碼來源:BenchmarkStatement.java

示例13: closeVerifyTimeout

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
private void closeVerifyTimeout(final ConsumerCoordinator coordinator,
        final long closeTimeoutMs, final long requestTimeoutMs,
        long expectedMinTimeMs, long expectedMaxTimeMs) throws Exception {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        boolean coordinatorUnknown = coordinator.coordinatorUnknown();
        // Run close on a different thread. Coordinator is locked by this thread, so it is
        // not safe to use the coordinator from the main thread until the task completes.
        Future<?> future = executor.submit(new Runnable() {
            @Override
            public void run() {
                coordinator.close(Math.min(closeTimeoutMs, requestTimeoutMs));
            }
        });
        // Wait for close to start. If coordinator is known, wait for close to queue
        // at least one request. Otherwise, sleep for a short time.
        if (!coordinatorUnknown)
            client.waitForRequests(1, 1000);
        else
            Thread.sleep(200);
        if (expectedMinTimeMs > 0) {
            time.sleep(expectedMinTimeMs - 1);
            try {
                future.get(500, TimeUnit.MILLISECONDS);
                fail("Close completed ungracefully without waiting for timeout");
            } catch (TimeoutException e) {
                // Expected timeout
            }
        }
        if (expectedMaxTimeMs >= 0)
            time.sleep(expectedMaxTimeMs - expectedMinTimeMs + 2);
        future.get(2000, TimeUnit.MILLISECONDS);
    } finally {
        executor.shutdownNow();
    }
}
 
開發者ID:YMCoding,項目名稱:kafka-0.11.0.0-src-with-comment,代碼行數:37,代碼來源:ConsumerCoordinatorTest.java

示例14: main

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
public static void main(String[] args)
{
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 5; i++)
    {
        exec.execute(new LiftOff2());
    }
    Thread.yield();
    exec.shutdownNow();
}
 
開發者ID:baohongfei,項目名稱:think-in-java,代碼行數:11,代碼來源:E20_InterruptCachedThreadPool.java

示例15: shutdownAndAwaitTermination

import java.util.concurrent.ExecutorService; //導入方法依賴的package包/類
/**
 * from javase7 doc
 * 
 * @param pool
 */
private void shutdownAndAwaitTermination(ExecutorService pool) {
	pool.shutdown(); // Disable new tasks from being submitted
	try {
		// Wait a while for existing tasks to terminate
		if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
			pool.shutdownNow(); // Cancel currently executing tasks
			// Wait a while for tasks to respond to being cancelled
			if (!pool.awaitTermination(5, TimeUnit.SECONDS))
				System.err.println("Pool did not terminate");
		}
	} catch (InterruptedException ie) {
		// (Re-)Cancel if current thread also interrupted
		pool.shutdownNow();
		// Preserve interrupt status
		Thread.currentThread().interrupt();
	}
}
 
開發者ID:quanqinle,項目名稱:WebAndAppUITesting,代碼行數:23,代碼來源:PerfMonitor.java


注:本文中的java.util.concurrent.ExecutorService.shutdownNow方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。