java.util.concurrent.ExecutorService

Here are the examples of the java api class java.util.concurrent.ExecutorService taken from open source projects.

1. MainActivity#runThreadPool()

Project: android-art-res
Source File: MainActivity.java
View license
private void runThreadPool() {
    Runnable command = new Runnable() {

        @Override
        public void run() {
            SystemClock.sleep(2000);
        }
    };
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
    fixedThreadPool.execute(command);
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    cachedThreadPool.execute(command);
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
    // 2000ms???command
    scheduledThreadPool.schedule(command, 2000, TimeUnit.MILLISECONDS);
    // ??10ms????1000ms????command
    scheduledThreadPool.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MILLISECONDS);
    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    singleThreadExecutor.execute(command);
}

2. PackageFactoryTest#testCreatePackageIsolatedFromOuterErrors()

Project: bazel
Source File: PackageFactoryTest.java
View license
@Test
public void testCreatePackageIsolatedFromOuterErrors() throws Exception {
    ExecutorService e = Executors.newCachedThreadPool();
    final Semaphore beforeError = new Semaphore(0);
    final Semaphore afterError = new Semaphore(0);
    Reporter reporter = new Reporter();
    ParsingTracker parser = new ParsingTracker(beforeError, afterError, reporter);
    final Logger log = Logger.getLogger(PackageFactory.class.getName());
    log.addHandler(parser);
    Level originalLevel = log.getLevel();
    log.setLevel(Level.FINE);
    e.execute(new ErrorReporter(reporter, beforeError, afterError));
    e.execute(parser);
    // wait for all to finish
    e.shutdown();
    assertTrue(e.awaitTermination(TestUtils.WAIT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS));
    log.removeHandler(parser);
    log.setLevel(originalLevel);
    assertTrue(parser.hasParsed());
}

3. CrawlerStopTest#whenStopIsCalledTheCrawlerStopsGracefully()

Project: crawljax
Source File: CrawlerStopTest.java
View license
@Test(timeout = 60_000)
public void whenStopIsCalledTheCrawlerStopsGracefully() throws Exception {
    CrawljaxConfigurationBuilder builder = SERVER.newConfigBuilder("infinite.html");
    CrawljaxRunner runner = new CrawljaxRunner(builder.setUnlimitedCrawlDepth().setUnlimitedCrawlDepth().setUnlimitedStates().build());
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(runner);
    Thread.sleep(TimeUnit.SECONDS.toMillis(15));
    runner.stop();
    executor.shutdown();
    executor.awaitTermination(30, TimeUnit.SECONDS);
    assertThat(runner.getReason(), is(ExitStatus.STOPPED));
}

4. ParallelIterate2Test#creationAndExecution()

View license
/**
     * crude test to check that creation works and that all tasks are executed
     */
@Test
public void creationAndExecution() throws InterruptedException {
    int howManyTimes = 200;
    AtomicInteger counter = new AtomicInteger(0);
    Collection<Callable<Integer>> tasks = new ArrayList<>();
    Interval.oneTo(howManyTimes).run(() -> tasks.add(counter::getAndIncrement));
    ExecutorService executorService1 = ParallelIterate.newPooledExecutor(4, "test pool 2 4", true);
    executorService1.invokeAll(tasks);
    Assert.assertEquals(howManyTimes, counter.get());
    counter.set(0);
    ExecutorService executorService2 = ParallelIterate.newPooledExecutor(2, "test pool 2", true);
    executorService2.invokeAll(tasks);
    Assert.assertEquals(howManyTimes, counter.get());
}

5. ParallelIterate2Test#creationAndExecution()

View license
/**
     * crude test to check that creation works and that all tasks are executed
     */
@Test
public void creationAndExecution() throws InterruptedException {
    int howManyTimes = 200;
    AtomicInteger counter = new AtomicInteger(0);
    Collection<Callable<Integer>> tasks = new ArrayList<>();
    Interval.oneTo(howManyTimes).run(() -> tasks.add(counter::getAndIncrement));
    ExecutorService executorService1 = ParallelIterate.newPooledExecutor(4, "test pool 2 4", true);
    executorService1.invokeAll(tasks);
    Assert.assertEquals(howManyTimes, counter.get());
    counter.set(0);
    ExecutorService executorService2 = ParallelIterate.newPooledExecutor(2, "test pool 2", true);
    executorService2.invokeAll(tasks);
    Assert.assertEquals(howManyTimes, counter.get());
}

6. IgniteExecutorServiceTest#testExecute()

View license
/**
     * @throws Exception Thrown in case of test failure.
     */
public void testExecute() throws Exception {
    Ignite ignite = G.ignite(getTestGridName());
    ExecutorService srvc = createExecutorService(ignite);
    srvc.execute(new Runnable() {

        @IgniteInstanceResource
        private Ignite ignite;

        @Override
        public void run() {
            System.out.println("Test message.");
            assert this.ignite != null;
        }
    });
    srvc.execute(new TestRunnable());
    srvc.shutdown();
}

7. ShouldNotDeadlockAnswerExecutionTest#failIfMockIsSharedBetweenThreads()

View license
@Test
public void failIfMockIsSharedBetweenThreads() throws Exception {
    Service service = Mockito.mock(Service.class);
    ExecutorService threads = Executors.newCachedThreadPool();
    AtomicInteger counter = new AtomicInteger(2);
    // registed answer on verySlowMethod
    Mockito.when(service.verySlowMethod()).thenAnswer(new LockingAnswer(counter));
    // execute verySlowMethod twice in separate threads
    threads.execute(new ServiceRunner(service));
    threads.execute(new ServiceRunner(service));
    // waiting for threads to finish
    threads.shutdown();
    if (!threads.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
        // threads were timed-out
        Assert.fail();
    }
}

8. SolrCoreTest#testReloadLeak()

Project: lucene-solr
Source File: SolrCoreTest.java
View license
/**
   * Test that's meant to be run with many iterations to expose a leak of SolrIndexSearcher when a core is closed
   * due to a reload. Without the fix, this test fails with most iters=1000 runs.
   */
@Test
public void testReloadLeak() throws Exception {
    final ExecutorService executor = ExecutorUtil.newMDCAwareFixedThreadPool(1, new DefaultSolrThreadFactory("testReloadLeak"));
    // Continuously open new searcher while core is not closed, and reload core to try to reproduce searcher leak.
    // While in practice we never continuously open new searchers, this is trying to make up for the fact that opening
    // a searcher in this empty core is very fast by opening new searchers continuously to increase the likelihood
    // for race.
    SolrCore core = h.getCore();
    assertTrue("Refcount != 1", core.getOpenCount() == 1);
    executor.execute(new NewSearcherRunnable(core));
    // Since we called getCore() vs getCoreInc() and don't own a refCount, the container should decRef the core
    // and close it when we call reload.
    h.reload();
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.MINUTES);
    // Check that all cores are closed and no searcher references are leaked.
    assertTrue("SolrCore " + core + " is not closed", core.isClosed());
    assertTrue(core.areAllSearcherReferencesEmpty());
}

9. CoreClientTest#testCoreClientWithInjectedThreadPools()

View license
@Test
public void testCoreClientWithInjectedThreadPools() throws Exception {
    ExecutorService threadPool = Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory());
    ScheduledThreadPoolExecutor scheduledThreadPool = new ScheduledThreadPoolExecutor(10);
    ServerLocator locator = createNonHALocator(false);
    boolean setThreadPools = locator.setThreadPools(threadPool, scheduledThreadPool);
    assertTrue(setThreadPools);
    testCoreClient(true, locator);
    threadPool.shutdown();
    scheduledThreadPool.shutdown();
    threadPool.awaitTermination(60, TimeUnit.SECONDS);
    scheduledThreadPool.awaitTermination(60, TimeUnit.SECONDS);
}

10. BlueprintTest#testCoordinationLifecycle()

Project: apache-aries
Source File: BlueprintTest.java
View license
@Test
public void testCoordinationLifecycle() throws InterruptedException, ExecutionException {
    CarService carService = getCarService("em");
    assertNoCars(carService);
    Runnable carLifeCycle = getService(Runnable.class, "(type=carCoordinated)");
    carLifeCycle.run();
    ExecutorService exec = Executors.newFixedThreadPool(20);
    List<Future<?>> futures = new ArrayList<Future<?>>();
    for (int c = 0; c < 100; c++) {
        futures.add(exec.submit(carLifeCycle));
    }
    exec.shutdown();
    exec.awaitTermination(30, TimeUnit.SECONDS);
    for (Future<?> future : futures) {
        future.get();
    }
    assertNoCars(carService);
}

11. BlueprintTest#testCoordinationLifecycle()

Project: aries
Source File: BlueprintTest.java
View license
@Test
public void testCoordinationLifecycle() throws InterruptedException, ExecutionException {
    CarService carService = getCarService("em");
    assertNoCars(carService);
    Runnable carLifeCycle = getService(Runnable.class, "(type=carCoordinated)");
    carLifeCycle.run();
    ExecutorService exec = Executors.newFixedThreadPool(20);
    List<Future<?>> futures = new ArrayList<Future<?>>();
    for (int c = 0; c < 100; c++) {
        futures.add(exec.submit(carLifeCycle));
    }
    exec.shutdown();
    exec.awaitTermination(30, TimeUnit.SECONDS);
    for (Future<?> future : futures) {
        future.get();
    }
    assertNoCars(carService);
}

12. DirectProducerBlockingTest#testProducerBlocksResumeTest()

View license
public void testProducerBlocksResumeTest() throws Exception {
    context.suspendRoute("foo");
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                log.info("Resuming consumer");
                context.resumeRoute("foo");
            } catch (Exception e) {
            }
        }
    });
    getMockEndpoint("mock:result").expectedMessageCount(1);
    template.sendBody("direct:suspended?block=true&timeout=5000", "hello world");
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

13. DirectVmProducerBlockingTest#testProducerBlocksResumeTest()

View license
public void testProducerBlocksResumeTest() throws Exception {
    context.suspendRoute("foo");
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                log.info("Resuming consumer");
                context.resumeRoute("foo");
            } catch (Exception e) {
            }
        }
    });
    getMockEndpoint("mock:result").expectedMessageCount(1);
    template.sendBody("direct-vm:suspended?block=true&timeout=5000", "hello world");
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

14. AggregateConcurrentPerCorrelationKeyTest#testAggregateConcurrentPerCorrelationKey()

View license
public void testAggregateConcurrentPerCorrelationKey() throws Exception {
    ExecutorService service = Executors.newFixedThreadPool(20);
    List<Callable<Object>> tasks = new ArrayList<Callable<Object>>();
    for (int i = 0; i < size; i++) {
        final int id = i % 5;
        final int count = i;
        tasks.add(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBodyAndHeader(uri, "" + count, "id", id);
                return null;
            }
        });
    }
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(5);
    // submit all tasks
    service.invokeAll(tasks);
    assertMockEndpointsSatisfied();
    service.shutdownNow();
}

15. StreamResequencerTest#testMultithreaded()

Project: camel
Source File: StreamResequencerTest.java
View license
public void testMultithreaded() throws Exception {
    int numMessages = 100;
    Object[] bodies = new Object[numMessages];
    for (int i = 0; i < numMessages; i++) {
        bodies[i] = "msg" + i;
    }
    getMockEndpoint("mock:result").expectedBodiesReceived(bodies);
    getMockEndpoint("mock:result").setResultWaitTime(20000);
    ProducerTemplate producerTemplate = context.createProducerTemplate();
    ProducerTemplate producerTemplate2 = context.createProducerTemplate();
    ExecutorService service = context.getExecutorServiceManager().newFixedThreadPool(this, getName(), 2);
    service.execute(new Sender(producerTemplate, 0, numMessages, 2));
    service.execute(new Sender(producerTemplate2, 1, numMessages, 2));
    assertMockEndpointsSatisfied();
    ServiceHelper.stopServices(producerTemplate, producerTemplate2);
}

16. SynchronousExecutorServiceTest#testSynchronousExecutorServiceShutdown()

View license
public void testSynchronousExecutorServiceShutdown() throws Exception {
    ExecutorService service = new SynchronousExecutorService();
    service.execute(new Runnable() {

        public void run() {
            invoked = true;
        }
    });
    service.shutdown();
    assertTrue(service.isShutdown());
    assertTrue(service.isTerminated());
}

17. LongOpOrderTest#testOrdering()

Project: cassandra
Source File: LongOpOrderTest.java
View license
@Test
public void testOrdering() throws InterruptedException {
    errors.set(0);
    Thread.setDefaultUncaughtExceptionHandler(handler);
    final ExecutorService exec = Executors.newCachedThreadPool(new NamedThreadFactory("checker"));
    final ScheduledExecutorService checker = Executors.newScheduledThreadPool(1, new NamedThreadFactory("checker"));
    for (int i = 0; i < CONSUMERS; i++) new TestOrdering(exec, checker);
    exec.shutdown();
    exec.awaitTermination((long) (RUNTIME * 1.1), TimeUnit.MILLISECONDS);
    assertTrue(exec.isShutdown());
    assertTrue(errors.get() == 0);
}

18. TcpManyClientConnectionsTest#test()

View license
/**
     * test many clients connecting to a single server
     */
@Test
public void test() throws IOException, InterruptedException {
    final ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < MAX; i++) {
        final int j = i;
        executorService.execute(() -> {
            maps[j].put("hello" + j, "world" + j);
            Assert.assertEquals("world" + j, maps[j].get("hello" + j));
        });
    }
    executorService.shutdown();
    executorService.awaitTermination(2, TimeUnit.SECONDS);
}

19. ConcurrentModelTest#testConcurrentInsert()

Project: DBFlow
Source File: ConcurrentModelTest.java
View license
@Test
public void testConcurrentInsert() throws InterruptedException {
    Delete.table(TestModel1.class);
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    for (int i = 0; i < CONCURRENT_INSERT_COUNT; i++) {
        // fails
        executorService.execute(new InsertRunnable());
    //executorService.execute(new PlainSqlInsertRunnable());    // passes
    }
    executorService.shutdown();
    executorService.awaitTermination(CONCURRENT_INSERT_TIMEOUT, TimeUnit.MILLISECONDS);
    long modelCount = selectCountOf().from(TestModel1.class).count();
    assertEquals(CONCURRENT_INSERT_COUNT, modelCount);
}

20. TestMTStmtNamedWindowJoinUniqueView#testJoin()

View license
public void testJoin() throws Exception {
    ExecutorService es = Executors.newFixedThreadPool(10);
    List<MyRunnable> runnables = new ArrayList<MyRunnable>();
    for (int i = 0; i < 6; i++) {
        runnables.add(new MyRunnable(service.getEPRuntime()));
    }
    for (Runnable toRun : runnables) {
        es.submit(toRun);
    }
    es.shutdown();
    es.awaitTermination(20, TimeUnit.SECONDS);
    for (MyRunnable runnable : runnables) {
        assertNull(runnable.getException());
    }
}

21. TestMTStmtStatelessEnummethod#tryCount()

View license
public void tryCount(int numThreads, int numMessages, String epl, GeneratorIteratorCallback generatorIteratorCallback) throws Exception {
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    EPStatement stmt = engine.getEPAdministrator().createEPL(epl);
    SupportUpdateListener listener = new SupportUpdateListener();
    stmt.addListener(listener);
    Future future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(new SendEventCallable(i, engine, new GeneratorIterator(numMessages, generatorIteratorCallback)));
    }
    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);
    for (int i = 0; i < numThreads; i++) {
        assertTrue((Boolean) future[i].get());
    }
    assertEquals(numMessages * numThreads, listener.getNewDataListFlattened().length);
}

22. GraphDatabaseStressTest#testConcurrentUses()

Project: geogig
Source File: GraphDatabaseStressTest.java
View license
@Test
public void testConcurrentUses() throws Exception {
    ConcurrentLinkedQueue<String> errorLog = new ConcurrentLinkedQueue<String>();
    // ExecutorService executor = Executors.newCachedThreadPool();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    List<Future<?>> futures = new ArrayList<Future<?>>();
    for (String s : new String[] { "a", "b", "c", "d" }) {
        Runnable task = new InsertMany(s, errorLog);
        futures.add(executor.submit(task));
    }
    for (Future<?> f : futures) {
        f.get();
    }
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.SECONDS);
    assertEquals(errorLog.toString(), 0, errorLog.size());
    assertEquals(100, database.getDepth(ObjectId.forString("a_commit_100")));
}

23. HawkBuilder#build()

Project: hawk
Source File: HawkBuilder.java
View license
public void build(final Callback callback) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(new Runnable() {

        @Override
        public void run() {
            try {
                startBuild();
                callback.onSuccess();
            } catch (Exception e) {
                callback.onFail(e);
            }
        }
    });
    executor.shutdown();
}

24. CascadedValidationTest#testCascadedValidationMultiThreaded()

View license
/**
	 * To be executed manually. Not part of the JMeter tests for now.
	 */
@Test
public void testCascadedValidationMultiThreaded() throws Exception {
    CountDownLatch startLatch = new CountDownLatch(1);
    ExecutorService executor = Executors.newFixedThreadPool(SIZE_OF_THREAD_POOL);
    for (int i = 0; i <= NUMBER_OF_RUNNABLES; i++) {
        Runnable run = new TestRunner(startLatch);
        executor.execute(run);
    }
    executor.shutdown();
    //start!
    startLatch.countDown();
    executor.awaitTermination(600, TimeUnit.SECONDS);
}

25. DataStoreUtil#importJobDataParallel()

Project: hydra
Source File: DataStoreUtil.java
View license
private static void importJobDataParallel(List<String> jobIds, SpawnDataStore sourceDataStore, SpawnDataStore targetDataStore, boolean checkAllWrites) throws Exception {
    ExecutorService executorService = new ThreadPoolExecutor(numCutoverThreads, numCutoverThreads, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
    AtomicBoolean gotFailures = new AtomicBoolean(false);
    int partitionSize = Math.max((int) Math.ceil((double) jobIds.size() / numCutoverThreads), 1);
    for (List<String> partition : Lists.partition(jobIds, partitionSize)) {
        executorService.submit(new CutoverWorker(sourceDataStore, targetDataStore, gotFailures, partition, checkAllWrites));
    }
    executorService.shutdown();
    executorService.awaitTermination(cutoverTimeoutMinutes, TimeUnit.MINUTES);
    if (gotFailures.get()) {
        throw new RuntimeException("A cutover worker has failed; see log for details");
    }
}

26. GridThreadPoolExecutorServiceSelfTest#testSingleThreadExecutor()

View license
/**
     * @throws Exception If failed.
     */
public void testSingleThreadExecutor() throws Exception {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.submit(new InterruptingRunnable()).get();
    // Thread is interrupted but Thread.interrupted() is called in AbstractQueuedSynchronizer.acquireInterruptibly
    // when blockingQueue wants to get the new task (see ThreadPoolExecutor.getTask()).
    // This will reset the interrupted flag. Any subsequent calls to Thread.currentThread.isInterrupted()
    // will return false.
    Future<Boolean> fut = exec.submit(new IsInterruptedAssertionCallable());
    assert !fut.get() : "Expecting the executorService to reset the interrupted flag when reinvoking the thread";
    exec.shutdown();
    assert exec.awaitTermination(30, SECONDS);
}

27. GridThreadPoolExecutorServiceSelfTest#testSingleGridThreadExecutor()

View license
/**
     * @throws Exception If failed.
     */
public void testSingleGridThreadExecutor() throws Exception {
    ExecutorService exec = Executors.newSingleThreadExecutor(new IgniteThreadFactory("gridName"));
    exec.submit(new InterruptingRunnable()).get();
    Future<Boolean> fut = exec.submit(new IsInterruptedAssertionCallable());
    assert !fut.get() : "Expecting the executorService to reset the interrupted flag when reinvoking the thread";
    // Thread is interrupted but Thread.interrupted() is called in AbstractQueuedSynchronizer.acquireInterruptibly
    // when blockingQueue wants to get the new task (see ThreadPoolExecutor.getTask()).
    // This will reset the interrupted flag but not the one from GridThread. Any subsequent calls to
    // Thread.currentThread.isInterrupted() will return true;
    exec.shutdown();
    assert exec.awaitTermination(30, SECONDS);
}

28. FillupMatrix#main()

Project: interview
Source File: FillupMatrix.java
View license
public static void main(String args[]) throws InterruptedException {
    int size = 5000;
    FillupMatrix fum = new FillupMatrix(size);
    ExecutorService executor = Executors.newFixedThreadPool(10);
    for (int i = 0; i < size * size; i++) {
        executor.execute(() -> fum.updateMatrix());
    }
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.SECONDS);
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            assert fum.getVal(i, j);
        }
    }
}

29. MinMaxKeeper#main()

Project: interview
Source File: MinMaxKeeper.java
View license
public static void main(String args[]) throws InterruptedException {
    ExecutorService executors = Executors.newFixedThreadPool(100);
    MinMaxKeeper mmKeeper = new MinMaxKeeper();
    for (int i = 0; i < 100000; i++) {
        GenerateRand rand = new GenerateRand(mmKeeper, i);
        executors.execute(rand);
    }
    executors.shutdown();
    executors.awaitTermination(10, TimeUnit.SECONDS);
    assert mmKeeper.getMin() == -1;
    assert mmKeeper.getMax() == 1000001;
}

30. LinkedTransferQueueTest#testOfferInExecutor()

Project: j2objc
Source File: LinkedTransferQueueTest.java
View license
/**
     * offer transfers elements across Executor tasks
     */
public void testOfferInExecutor() {
    final LinkedTransferQueue q = new LinkedTransferQueue();
    final CheckedBarrier threadsStarted = new CheckedBarrier(2);
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            threadsStarted.await();
            assertTrue(q.offer(one, LONG_DELAY_MS, MILLISECONDS));
        }
    });
    executor.execute(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            threadsStarted.await();
            assertSame(one, q.take());
            checkEmpty(q);
        }
    });
    joinPool(executor);
}

31. LinkedTransferQueueTest#testPollInExecutor()

Project: j2objc
Source File: LinkedTransferQueueTest.java
View license
/**
     * timed poll retrieves elements across Executor threads
     */
public void testPollInExecutor() {
    final LinkedTransferQueue q = new LinkedTransferQueue();
    final CheckedBarrier threadsStarted = new CheckedBarrier(2);
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            assertNull(q.poll());
            threadsStarted.await();
            assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
            checkEmpty(q);
        }
    });
    executor.execute(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            threadsStarted.await();
            q.put(one);
        }
    });
    joinPool(executor);
}

32. ConcurrentWriteMultipleMkMongoTest#doTest()

View license
private void doTest(int numberOfNodes) throws Exception {
    int numberOfChildren = 10;
    int numberOfMks = 3;
    String[] prefixes = new String[] { "a", "b", "c", "d", "e", "f" };
    ExecutorService executor = Executors.newFixedThreadPool(numberOfMks);
    List<DocumentMK> mks = new ArrayList<DocumentMK>();
    for (int i = 0; i < numberOfMks; i++) {
        String diff = buildPyramidDiff("/", 0, numberOfChildren, numberOfNodes, prefixes[i], new StringBuilder()).toString();
        DocumentMK mk = new DocumentMK.Builder().open();
        mks.add(mk);
        GenericWriteTask task = new GenericWriteTask("mk-" + i, mk, diff, 10);
        executor.execute(task);
    }
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.MINUTES);
    for (DocumentMK mk : mks) {
        mk.dispose();
    }
}

33. JUConcurrentTests#futureTask()

View license
@RaceTest(expectRace = false, description = "Test happens-before relations between FutureTask calculation and get")
public void futureTask() {
    FutureTask<int[]> future = new FutureTask<int[]>(new Callable<int[]>() {

        public int[] call() {
            int[] res = new int[1];
            res[0] = 42;
            return res;
        }
    });
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(future);
    try {
        int[] futureRes = future.get();
        futureRes[0]++;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    executor.shutdown();
}

34. Lock2#main()

Project: java8-tutorial
Source File: Lock2.java
View license
public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    ReentrantLock lock = new ReentrantLock();
    executor.submit(() -> {
        lock.lock();
        try {
            ConcurrentUtils.sleep(1);
        } finally {
            lock.unlock();
        }
    });
    executor.submit(() -> {
        System.out.println("Locked: " + lock.isLocked());
        System.out.println("Held by me: " + lock.isHeldByCurrentThread());
        boolean locked = lock.tryLock();
        System.out.println("Lock acquired: " + locked);
    });
    ConcurrentUtils.stop(executor);
}

35. FileAppenderTest#testMultipleAppenders()

View license
@Test
public void testMultipleAppenders() throws Exception {
    final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
    final Exception[] error = new Exception[1];
    final int count = 100;
    final Runnable runnable = new FileWriterRunnable(false, count, error);
    for (int i = 0; i < THREADS; ++i) {
        pool.execute(runnable);
    }
    pool.shutdown();
    pool.awaitTermination(10, TimeUnit.SECONDS);
    if (error[0] != null) {
        throw error[0];
    }
    verifyFile(THREADS * count);
}

36. FileAppenderTest#testMultipleLockedAppenders()

View license
@Test
public void testMultipleLockedAppenders() throws Exception {
    final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
    final Exception[] error = new Exception[1];
    final int count = 100;
    final Runnable runnable = new FileWriterRunnable(true, count, error);
    for (int i = 0; i < THREADS; ++i) {
        pool.execute(runnable);
    }
    pool.shutdown();
    pool.awaitTermination(10, TimeUnit.SECONDS);
    if (error[0] != null) {
        throw error[0];
    }
    verifyFile(THREADS * count);
}

37. HealthCheckRegistryTest#runsRegisteredHealthChecksInParallel()

View license
@Test
public void runsRegisteredHealthChecksInParallel() throws Exception {
    final ExecutorService executor = Executors.newFixedThreadPool(10);
    final Map<String, HealthCheck.Result> results = registry.runHealthChecks(executor);
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.SECONDS);
    assertThat(results).contains(entry("hc1", r1));
    assertThat(results).contains(entry("hc2", r2));
}

38. HttpOverSpdyTest#synchronousSpdyRequest()

Project: okhttp
Source File: HttpOverSpdyTest.java
View license
@Test
@Ignore
public void synchronousSpdyRequest() throws Exception {
    server.enqueue(new MockResponse().setBody("A"));
    server.enqueue(new MockResponse().setBody("A"));
    ExecutorService executor = Executors.newCachedThreadPool();
    CountDownLatch countDownLatch = new CountDownLatch(2);
    executor.execute(new SpdyRequest("/r1", countDownLatch));
    executor.execute(new SpdyRequest("/r2", countDownLatch));
    countDownLatch.await();
    assertEquals(0, server.takeRequest().getSequenceNumber());
    assertEquals(1, server.takeRequest().getSequenceNumber());
}

39. BlockingBooleanTest#waitSame()

Project: onos
Source File: BlockingBooleanTest.java
View license
@Test
public void waitSame() {
    BlockingBoolean b = new BlockingBoolean(true);
    CountDownLatch latch = new CountDownLatch(1);
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.submit(() -> {
        try {
            b.await(true);
            latch.countDown();
        } catch (InterruptedException e) {
            fail();
        }
    });
    try {
        assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        fail();
    }
    exec.shutdown();
}

40. BlockingBooleanTest#waitTimeout()

Project: onos
Source File: BlockingBooleanTest.java
View license
@Test
public void waitTimeout() {
    BlockingBoolean b = new BlockingBoolean(true);
    CountDownLatch latch = new CountDownLatch(1);
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.submit(() -> {
        try {
            if (!b.await(false, 1, TimeUnit.NANOSECONDS)) {
                latch.countDown();
            } else {
                fail();
            }
        } catch (InterruptedException e) {
            fail();
        }
    });
    try {
        assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        fail();
    }
    exec.shutdown();
}

41. ParkLoops#main()

Project: openjdk
Source File: ParkLoops.java
View license
public static void main(String[] args) throws Exception {
    final SplittableRandom rnd = new SplittableRandom();
    final ExecutorService pool = Executors.newCachedThreadPool();
    final AtomicReferenceArray<Thread> threads = new AtomicReferenceArray<>(THREADS);
    final CountDownLatch done = new CountDownLatch(THREADS);
    for (int i = 0; i < THREADS; i++) {
        pool.submit(new Parker(threads, done, rnd.split()));
        pool.submit(new Unparker(threads, done, rnd.split()));
    }
    // Let test harness handle timeout
    done.await();
    pool.shutdown();
    pool.awaitTermination(Long.MAX_VALUE, SECONDS);
}

42. RedisBFPerformance#dumbParallelAdds()

View license
private static void dumbParallelAdds(int count, int items, BloomFilter<String> b) throws Exception {
    b.clear();
    Random r = new Random();
    ExecutorService exec = Executors.newFixedThreadPool(20);
    long start = System.currentTimeMillis();
    IntStream.range(0, count).forEach( i -> {
        exec.submit(() -> b.add(String.valueOf(r.nextInt(items))));
    });
    exec.shutdown();
    exec.awaitTermination(5, TimeUnit.SECONDS);
    long end = System.currentTimeMillis();
    MemoryBFTest.printStat(start, end, count);
}

43. StarTreeClusterIntegrationTest#generateAndUploadSegments()

View license
/**
   * Generate the reference and star tree indexes and upload to corresponding tables.
   * @param avroFiles
   * @param tableName
   * @param starTree
   * @throws IOException
   * @throws ArchiveException
   * @throws InterruptedException
   */
private void generateAndUploadSegments(List<File> avroFiles, String tableName, boolean starTree) throws IOException, ArchiveException, InterruptedException {
    BaseClusterIntegrationTest.ensureDirectoryExistsAndIsEmpty(_segmentsDir);
    BaseClusterIntegrationTest.ensureDirectoryExistsAndIsEmpty(_tarredSegmentsDir);
    ExecutorService executor = Executors.newCachedThreadPool();
    BaseClusterIntegrationTest.buildSegmentsFromAvro(avroFiles, executor, 0, _segmentsDir, _tarredSegmentsDir, tableName, starTree, null);
    executor.shutdown();
    executor.awaitTermination(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    for (String segmentName : _tarredSegmentsDir.list()) {
        LOGGER.info("Uploading segment {}", segmentName);
        File file = new File(_tarredSegmentsDir, segmentName);
        FileUploadUtils.sendSegmentFile(ControllerTestUtils.DEFAULT_CONTROLLER_HOST, ControllerTestUtils.DEFAULT_CONTROLLER_API_PORT, segmentName, new FileInputStream(file), file.length());
    }
}

44. ScanBasedQueryProcessor#processSegments()

Project: pinot
Source File: ScanBasedQueryProcessor.java
View license
private List<ResultTable> processSegments(final String query, final BrokerRequest brokerRequest) throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    final List<ResultTable> resultTables = Collections.synchronizedList(new ArrayList<ResultTable>());
    for (final SegmentQueryProcessor segmentQueryProcessor : _segmentQueryProcessorMap.values()) {
        executorService.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    ResultTable resultTable = segmentQueryProcessor.process(brokerRequest);
                    if (resultTable != null) {
                        resultTables.add(resultTable);
                    }
                } catch (Exception e) {
                    LOGGER.error("Exception caught while processing segment '{}'.", segmentQueryProcessor.getSegmentName(), e);
                    return;
                }
            }
        });
    }
    executorService.shutdown();
    executorService.awaitTermination(_timeoutInSeconds, TimeUnit.SECONDS);
    return resultTables;
}

45. TicksTest#executorTest()

Project: ReactFX
Source File: TicksTest.java
View license
@Test
public void executorTest() throws InterruptedException, ExecutionException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    CompletableFuture<Integer> nTicks = new CompletableFuture<>();
    executor.execute(() -> {
        EventCounter counter = new EventCounter();
        Subscription sub = EventStreams.ticks(Duration.ofMillis(100), scheduler, executor).subscribe(counter::accept);
        // stop after 3 ticks
        ScheduledExecutorServiceTimer.create(Duration.ofMillis(350), sub::unsubscribe, scheduler, executor).restart();
        // wait a little more to test that no more than 3 ticks arrive anyway
        ScheduledExecutorServiceTimer.create(Duration.ofMillis(550), () -> nTicks.complete(counter.get()), scheduler, executor).restart();
    });
    assertEquals(3, nTicks.get().intValue());
    executor.shutdown();
}

46. ConcurrentJcrResourceBundleLoadingTest#loadBundlesOnlyOnceWithConcurrentRequests()

View license
@Test
public void loadBundlesOnlyOnceWithConcurrentRequests() throws Exception {
    final int numberOfThreads = 40;
    final ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads / 2);
    for (int i = 0; i < numberOfThreads; i++) {
        final Locale language = i < numberOfThreads / 2 ? Locale.ENGLISH : Locale.GERMAN;
        executor.submit(new Runnable() {

            @Override
            public void run() {
                provider.getResourceBundle(language);
            }
        });
    }
    executor.shutdown();
    executor.awaitTermination(5, TimeUnit.SECONDS);
    verifyPrivate(provider, times(1)).invoke("createResourceBundle", eq(null), eq(Locale.ENGLISH));
    verifyPrivate(provider, times(1)).invoke("createResourceBundle", eq(null), eq(Locale.GERMAN));
}

47. ThreadScopeSessionBeanTest#ShouldUseDifferentSessionForSessionBeansOnDifferentThreads()

View license
@Test
public void ShouldUseDifferentSessionForSessionBeansOnDifferentThreads() throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 2; i++) {
        final int j = i;
        executor.submit(new Runnable() {

            @Override
            public void run() {
                // captures the session's JVM identity
                sessions[j] = session.toString();
            }
        });
    }
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.MINUTES);
    Assert.assertFalse(sessions[0].equals(sessions[1]));
}

48. LongOpOrderTest#testOrdering()

View license
@Test
public void testOrdering() throws InterruptedException {
    errors.set(0);
    Thread.setDefaultUncaughtExceptionHandler(handler);
    final ExecutorService exec = Executors.newCachedThreadPool(new NamedThreadFactory("checker"));
    final ScheduledExecutorService checker = Executors.newScheduledThreadPool(1, new NamedThreadFactory("checker"));
    for (int i = 0; i < CONSUMERS; i++) new TestOrdering(exec, checker);
    exec.shutdown();
    exec.awaitTermination((long) (RUNTIME * 1.1), TimeUnit.MILLISECONDS);
    assertTrue(exec.isShutdown());
    assertTrue(errors.get() == 0);
}

49. TestAsyncSuroSender#testMultithread()

Project: suro
Source File: TestAsyncSuroSender.java
View license
@Test
public void testMultithread() throws InterruptedException {
    AsyncSuroClient client = injector.getInstance(AsyncSuroClient.class);
    ExecutorService executors = Executors.newFixedThreadPool(3);
    for (int i = 0; i < 10; ++i) {
        executors.submit(new AsyncSuroSender(TestConnectionPool.createMessageSet(100), client, injector.getInstance(ClientConfig.class)));
    }
    executors.shutdown();
    executors.awaitTermination(10, TimeUnit.SECONDS);
    TestConnectionPool.checkMessageSetCount(servers, 10, true);
    assertEquals(client.getSentMessageCount(), 1000);
}

50. ReferenceCounterTest#testReferenceValidExecutorUsed()

View license
@Test
public void testReferenceValidExecutorUsed() throws Exception {
    ExecutorService executor = Executors.newSingleThreadExecutor(ActiveMQThreadFactory.defaultThreadFactory());
    LatchRunner runner = new LatchRunner();
    ReferenceCounterUtil counter = new ReferenceCounterUtil(runner, executor);
    counter.increment();
    counter.decrement();
    runner.latch.await(5, TimeUnit.SECONDS);
    assertNotSame(runner.lastThreadUsed, Thread.currentThread());
    executor.shutdown();
}

51. UnlimitedEnqueueTest#testEnqueueIsOnlyLimitedByDisk()

View license
@Test
public void testEnqueueIsOnlyLimitedByDisk() throws Exception {
    ExecutorService executor = Executors.newCachedThreadPool();
    for (int i = 0; i < numThreads; i++) {
        executor.execute(new Producer(numMessages / numThreads));
    }
    assertTrue("Temp Store is filling ", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            LOG.info("Temp Usage,  " + brokerService.getSystemUsage().getTempUsage() + ", full=" + brokerService.getSystemUsage().getTempUsage().isFull() + ", % usage: " + brokerService.getSystemUsage().getTempUsage().getPercentUsage());
            return brokerService.getSystemUsage().getTempUsage().getPercentUsage() > 1;
        }
    }, TimeUnit.MINUTES.toMillis(4)));
    executor.shutdownNow();
}

52. SimpleKeyStoreLoader#loadAsync()

View license
@Override
public Future<JsonNode> loadAsync(final EndPoint endPoint) {
    if (endPoint == null) {
        throw new PreconditionException("Required parameter is null");
    }
    final ExecutorService executorService = Executors.newSingleThreadExecutor();
    final Future<JsonNode> future = executorService.submit(new Callable<JsonNode>() {

        public JsonNode call() throws Exception {
            return load(endPoint);
        }
    });
    executorService.shutdown();
    return future;
}

53. MultiThreadedDBSearch#interrupt()

Project: biojava
Source File: MultiThreadedDBSearch.java
View license
/** stops what is currently happening and does not continue
	 *
	 *
	 */
public void interrupt() {
    interrupted.set(true);
    ExecutorService pool = ConcurrencyTools.getThreadPool();
    pool.shutdownNow();
    try {
        DomainProvider domainProvider = DomainProviderFactory.getDomainProvider();
        if (domainProvider instanceof RemoteDomainProvider) {
            RemoteDomainProvider remote = (RemoteDomainProvider) domainProvider;
            remote.flushCache();
        }
    } catch (IOException e) {
    }
}

54. CommonTestUtils#startThreadTest()

Project: bonecp
Source File: CommonTestUtils.java
View license
/**
	 * Helper function.
	 *
	 * @param threads
	 * @param connections
	 * @param cpds
	 * @param workDelay
	 * @param doPreparedStatement 
	 * @return time taken
	 * @throws InterruptedException
	 */
public static long startThreadTest(int threads, long connections, DataSource cpds, int workDelay, boolean doPreparedStatement) throws InterruptedException {
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(threads);
    ExecutorService pool = Executors.newFixedThreadPool(threads);
    for (// create and start threads
    int i = 0; // create and start threads
    i < threads; // create and start threads
    i++) {
        pool.execute(new ThreadTester(startSignal, doneSignal, cpds, connections, workDelay, doPreparedStatement));
    }
    long start = System.currentTimeMillis();
    // START TEST!
    startSignal.countDown();
    doneSignal.await();
    long end = (System.currentTimeMillis() - start);
    pool.shutdown();
    return end;
}

55. TestCustomThreadFactory#testUncaughtException()

Project: bonecp
Source File: TestCustomThreadFactory.java
View license
/** Tests the uncaught exception handler. 
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InterruptedException
	 */
@Test
public void testUncaughtException() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InterruptedException {
    CustomThreadFactory testClass = new CustomThreadFactory("test", false);
    Logger mockLogger = TestUtils.mockLogger(testClass.getClass());
    makeThreadSafe(mockLogger, true);
    ExecutorService executor = Executors.newSingleThreadExecutor(testClass);
    mockLogger.error((String) anyObject(), (Throwable) anyObject());
    expectLastCall().once();
    replay(mockLogger);
    executor.execute(new MockThread());
    for (int i = 0; i < 5; i++) {
        signalled = true;
        Thread.sleep(400);
    }
    verify(mockLogger);
}

56. BenchmarkTests#startThreadTest()

Project: bonecp
Source File: BenchmarkTests.java
View license
/**
	 * Helper function.
	 *
	 * @param threads
	 * @param cpds
	 * @param workDelay
	 * @param doPreparedStatement 
	 * @return time taken
	 * @throws InterruptedException
	 */
public static long startThreadTest(int threads, DataSource cpds, int workDelay, boolean doPreparedStatement) throws InterruptedException {
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(threads);
    ExecutorService pool = Executors.newFixedThreadPool(threads);
    ExecutorCompletionService<Long> ecs = new ExecutorCompletionService<Long>(pool);
    for (// create and start threads
    int i = 0; // create and start threads
    i <= threads; // create and start threads
    i++) {
        ecs.submit(new ThreadTesterUtil(startSignal, doneSignal, cpds, workDelay, doPreparedStatement));
    }
    // START TEST!
    startSignal.countDown();
    doneSignal.await();
    long time = 0;
    for (int i = 0; i <= threads; i++) {
        try {
            time = time + ecs.take().get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    pool.shutdown();
    return time;
}

57. VersionControlStatsGeneratorTest#sameThreadExecutorService()

View license
private ExecutorService sameThreadExecutorService() {
    ExecutorService executorService = createMock(ExecutorService.class);
    executorService.submit(anyObject(Runnable.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            Runnable runnable = (Runnable) getCurrentArguments()[0];
            runnable.run();
            return null;
        }
    }).anyTimes();
    replay(executorService);
    return executorService;
}

58. ThreadPoolBuilderTest#testThreadPoolBuilderTwoPoolsDefault()

Project: camel
Source File: ThreadPoolBuilderTest.java
View license
public void testThreadPoolBuilderTwoPoolsDefault() throws Exception {
    ThreadPoolBuilder builder = new ThreadPoolBuilder(context);
    ExecutorService executor = builder.build(this, "myPool");
    ExecutorService executor2 = builder.build(this, "myOtherPool");
    assertNotNull(executor);
    assertNotNull(executor2);
    assertEquals(false, executor.isShutdown());
    assertEquals(false, executor2.isShutdown());
    context.stop();
    assertEquals(true, executor.isShutdown());
    assertEquals(true, executor2.isShutdown());
}

59. SedaConcurrentTest#testSedaConcurrentInOut()

Project: camel
Source File: SedaConcurrentTest.java
View license
public void testSedaConcurrentInOut() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(20);
    mock.allMessages().body().startsWith("Bye");
    // should at least take 3 sec
    mock.setResultMinimumWaitTime(3000);
    ExecutorService executors = Executors.newFixedThreadPool(10);
    List<Object> replies = new ArrayList<Object>(20);
    for (int i = 0; i < 20; i++) {
        final int num = i;
        Object out = executors.submit(new Callable<Object>() {

            public Object call() throws Exception {
                return template.requestBody("seda:bar", "Message " + num);
            }
        });
        replies.add(out);
    }
    assertMockEndpointsSatisfied();
    assertEquals(20, replies.size());
    executors.shutdownNow();
}

60. XPathAnotherRouteConcurrentTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:claus").expectedMessageCount(files / 2);
    getMockEndpoint("mock:james").expectedMessageCount(files / 2);
    getMockEndpoint("mock:claus").expectsNoDuplicates(body());
    getMockEndpoint("mock:james").expectsNoDuplicates(body());
    getMockEndpoint("mock:other").expectedMessageCount(0);
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                if (index % 2 == 0) {
                    template.sendBody("seda:foo", createXmlBody(index, "Claus"));
                } else {
                    template.sendBody("seda:foo", createXmlBody(index, "James"));
                }
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdown();
}

61. MulticastParallelStressTest#testConcurrencyParallelMulticast()

View license
public void testConcurrencyParallelMulticast() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(20);
    // this time we cannot expect in order but there should be no duplicates
    mock.expectsNoDuplicates(header("id"));
    ExecutorService executor = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 20; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBodyAndHeader("direct:start", "", "id", index);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

62. SamplingThrottlerTest#testSendLotsOfMessagesSimultaneouslyButOnly3GetThrough()

Project: camel
Source File: SamplingThrottlerTest.java
View license
public void testSendLotsOfMessagesSimultaneouslyButOnly3GetThrough() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMinimumMessageCount(3);
    mock.setResultWaitTime(4000);
    final List<Exchange> sentExchanges = Collections.synchronizedList(new ArrayList<Exchange>());
    ExecutorService executor = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 5; i++) {
        executor.execute(new Runnable() {

            public void run() {
                try {
                    sendExchangesThroughDroppingThrottler(sentExchanges, 35);
                } catch (Exception e) {
                }
            }
        });
    }
    mock.assertIsSatisfied();
    executor.shutdownNow();
}

63. ThrottlerAsyncDelayedTest#testSendLotsOfMessagesSimultaneouslyButOnly3GetThrough()

View license
public void testSendLotsOfMessagesSimultaneouslyButOnly3GetThrough() throws Exception {
    long start = System.currentTimeMillis();
    MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class);
    resultEndpoint.expectedMessageCount(messageCount);
    ExecutorService executor = Executors.newFixedThreadPool(messageCount);
    for (int i = 0; i < messageCount; i++) {
        executor.execute(new Runnable() {

            public void run() {
                template.sendBody("direct:a", "<message>payload</message>");
            }
        });
    }
    // let's wait for the exchanges to arrive
    resultEndpoint.assertIsSatisfied();
    // now assert that they have actually been throttled
    long minimumTime = (messageCount - 1) * INTERVAL;
    // add a little slack
    long delta = System.currentTimeMillis() - start + 200;
    assertTrue("Should take at least " + minimumTime + "ms, was: " + delta, delta >= minimumTime);
    executor.shutdownNow();
}

64. SynchronousExecutorServiceTest#testSynchronousExecutorService()

View license
public void testSynchronousExecutorService() throws Exception {
    name1 = Thread.currentThread().getName();
    ExecutorService service = new SynchronousExecutorService();
    service.execute(new Runnable() {

        public void run() {
            invoked = true;
            name2 = Thread.currentThread().getName();
        }
    });
    assertTrue("Should have been invoked", invoked);
    assertEquals("Should use same thread", name1, name2);
}

65. BoonConcurrentTest#doSendMessages()

Project: camel
Source File: BoonConcurrentTest.java
View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                TestPojo pojo = new TestPojo();
                pojo.setName("Hi " + index);
                template.sendBody("direct:start", pojo);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

66. FreemarkerConcurrentTest#doSendMessages()

Project: camel
Source File: FreemarkerConcurrentTest.java
View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    getMockEndpoint("mock:result").message(0).body().contains("Bye");
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBody("direct:start", "Hello " + index);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

67. FtpProducerConcurrentTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        getMockEndpoint("mock:result").expectedFileExists(FTP_ROOT_DIR + "/concurrent/" + i + ".txt");
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                sendFile("direct:start", "Hello World", index + ".txt");
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

68. GsonConcurrentTest#doSendMessages()

Project: camel
Source File: GsonConcurrentTest.java
View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                TestPojo pojo = new TestPojo();
                pojo.setName("Hi " + index);
                template.sendBody("direct:start", pojo);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

69. HawtDBAggregateConcurrentDifferentGroupsTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:aggregated");
    mock.expectedMessageCount(2);
    mock.setResultWaitTime(30 * 1000L);
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                String id = index % 2 == 0 ? "A" : "B";
                template.sendBodyAndHeader("direct:start", index, "id", id);
                // simulate a little delay
                Thread.sleep(3);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

70. HawtDBAggregateConcurrentSameGroupTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:aggregated");
    mock.setResultWaitTime(30 * 1000L);
    mock.expectedMessageCount(1);
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBodyAndHeader("direct:start", index, "id", 123);
                // simulate a little delay
                Thread.sleep(3);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

71. JacksonConcurrentTest#doSendMessages()

Project: camel
Source File: JacksonConcurrentTest.java
View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                TestPojo pojo = new TestPojo();
                pojo.setName("Hi " + index);
                template.sendBody("direct:start", pojo);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

72. JacksonConcurrentTest#doSendMessages()

Project: camel
Source File: JacksonConcurrentTest.java
View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                TestPojo pojo = new TestPojo();
                pojo.setName("Hi " + index);
                template.sendBody("direct:start", pojo);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

73. JavaSpaceRequestReplyTest#testJavaSpaceConcurrentRequestReply()

View license
@Test
public void testJavaSpaceConcurrentRequestReply() throws Exception {
    Vector<FutureTask<Reply>> tasks = new Vector<FutureTask<Reply>>();
    Endpoint endpoint = context.getEndpoint("direct:input");
    ExecutorService es = Executors.newFixedThreadPool(10);
    long start = System.currentTimeMillis();
    for (int i = 0; i < 100; ++i) {
        Request req = new Request();
        req.setPayload("REQUEST " + i);
        ITestPojo proxy = ProxyHelper.createProxy(endpoint, ITestPojo.class);
        FutureTask<Reply> task = new FutureTask<Reply>(new PojoCallable(req, proxy));
        tasks.add(task);
        es.submit(task);
    }
    int i = 0;
    for (FutureTask<Reply> futureTask : tasks) {
        assertTrue(futureTask.get().getPayload().equals("REPLY for REQUEST " + i++));
    }
    long stop = System.currentTimeMillis();
    log.info("{} took {} milliseconds", getTestMethodName(), stop - start);
    es.shutdownNow();
}

74. JaxbConcurrentDataFormatTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                PurchaseOrder bean = new PurchaseOrder();
                bean.setName("Beer");
                bean.setAmount(Double.valueOf("" + index));
                bean.setPrice(Double.valueOf("" + index) * 2);
                template.sendBody("direct:start", bean);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

75. JmsDefaultTaskExecutorTypeTest#doSendMessages()

View license
private void doSendMessages(final String queueName, int messages, int poolSize, final DefaultTaskExecutorType defaultTaskExecutorType) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    final CountDownLatch latch = new CountDownLatch(messages);
    for (int i = 0; i < messages; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                String options = defaultTaskExecutorType == null ? "" : "?defaultTaskExecutorType=" + defaultTaskExecutorType.toString();
                template.requestBody("activemq:queue:" + queueName + options, "Message " + index);
                latch.countDown();
                return null;
            }
        });
    }
    latch.await();
    executor.shutdown();
}

76. JmsProduerConcurrentTest#doSendMessages()

Project: camel
Source File: JmsProduerConcurrentTest.java
View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").expectsNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBody("direct:start", "Message " + index);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

77. JmsProduerConcurrentWithReplyTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").expectsNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    final List<Future<String>> futures = new ArrayList<Future<String>>();
    for (int i = 0; i < files; i++) {
        final int index = i;
        Future<String> out = executor.submit(new Callable<String>() {

            public String call() throws Exception {
                return template.requestBody("direct:start", "Message " + index, String.class);
            }
        });
        futures.add(out);
    }
    assertMockEndpointsSatisfied();
    for (int i = 0; i < futures.size(); i++) {
        Object out = futures.get(i).get();
        assertEquals("Bye Message " + i, out);
    }
    executor.shutdownNow();
}

78. JmsRouteUsingJMSXGroupTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files * 2);
    getMockEndpoint("mock:result").expectsNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBodyAndHeader("direct:start", "IBM: " + index, JMS_X_GROUP_ID, "IBM");
                template.sendBodyAndHeader("direct:start", "SUN: " + index, JMS_X_GROUP_ID, "SUN");
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

79. LevelDBAggregateConcurrentDifferentGroupsTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:aggregated");
    mock.expectedMessageCount(2);
    mock.setResultWaitTime(30 * 1000L);
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                String id = index % 2 == 0 ? "A" : "B";
                template.sendBodyAndHeader("direct:start", index, "id", id);
                // simulate a little delay
                Thread.sleep(3);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

80. LevelDBAggregateConcurrentSameGroupTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:aggregated");
    mock.setResultWaitTime(30 * 1000L);
    mock.expectedMessageCount(1);
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBodyAndHeader("direct:start", index, "id", 123);
                // simulate a little delay
                Thread.sleep(3);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

81. RmiConcurrencyTest#doSendMessages()

Project: camel
Source File: RmiConcurrencyTest.java
View license
private void doSendMessages(int files, int poolSize) throws Exception {
    if (classPathHasSpaces()) {
        return;
    }
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    getMockEndpoint("mock:result").message(0).body().contains("Echo");
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBody("direct:echo", "" + index);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

82. InOutConcurrentConsumerTest#doSendMessages()

View license
private void doSendMessages(int messages, int poolSize) throws Exception {
    result.expectedMessageCount(messages);
    result.expectsNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    final List<Future<String>> futures = new ArrayList<Future<String>>();
    for (int i = 0; i < messages; i++) {
        final int index = i;
        Future<String> out = executor.submit(new Callable<String>() {

            public String call() throws Exception {
                return template.requestBody("direct:start", "Message " + index, String.class);
            }
        });
        futures.add(out);
    }
    assertMockEndpointsSatisfied();
    for (int i = 0; i < futures.size(); i++) {
        Object out = futures.get(i).get();
        assertEquals("Bye Message " + i, out);
    }
    executor.shutdownNow();
}

83. JdbcAggregateConcurrentDifferentGroupsTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:aggregated");
    mock.expectedMessageCount(2);
    mock.setResultWaitTime(30 * 1000L);
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                String id = index % 2 == 0 ? "A" : "B";
                template.sendBodyAndHeader("direct:start", index, "id", id);
                // simulate a little delay
                Thread.sleep(3);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

84. JdbcAggregateConcurrentSameGroupTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:aggregated");
    mock.setResultWaitTime(30 * 1000L);
    mock.expectedMessageCount(1);
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBodyAndHeader("direct:start", index, "id", 123);
                // simulate a little delay
                Thread.sleep(3);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

85. StringTemplateConcurrentTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    getMockEndpoint("mock:result").message(0).body().contains("Bye");
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBody("direct:start", "Hello " + index);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

86. VelocityConcurrentTest#doSendMessages()

Project: camel
Source File: VelocityConcurrentTest.java
View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    getMockEndpoint("mock:result").message(0).body().contains("Bye");
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBody("direct:start", "Hello " + index);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

87. XMLSecurityConcurrencyTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:secure").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                String body = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><body>you can not read me " + index + "</body>";
                template.sendBody("direct:start", body);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    String secure = getMockEndpoint("mock:secure").getReceivedExchanges().get(0).getIn().getBody(String.class);
    assertNotNull(secure);
    assertTrue("Should not be readable", secure.indexOf("read") == -1);
    executor.shutdownNow();
}

88. XmppProducerConcurrentTest#doSendMessages()

View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.sendBody("direct:start", "Hello " + index);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

89. XStreamConcurrencyTest#doSendMessages()

Project: camel
Source File: XStreamConcurrencyTest.java
View license
private void doSendMessages(int files, int poolSize) throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(files);
    getMockEndpoint("mock:result").assertNoDuplicates(body());
    ExecutorService executor = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < files; i++) {
        final int index = i;
        executor.submit(new Callable<Object>() {

            public Object call() throws Exception {
                PurchaseOrder bean = new PurchaseOrder();
                bean.setName("Beer");
                bean.setAmount(Double.valueOf("" + index));
                bean.setPrice(Double.valueOf("" + index) * 2);
                template.sendBody("direct:start", bean);
                return null;
            }
        });
    }
    assertMockEndpointsSatisfied();
    executor.shutdownNow();
}

90. MonitoringTaskTest#testMultipleThreads()

Project: cassandra
Source File: MonitoringTaskTest.java
View license
@Test
public void testMultipleThreads() throws InterruptedException {
    final int opCount = 50;
    final ExecutorService executorService = Executors.newFixedThreadPool(20);
    final List<Monitorable> operations = Collections.synchronizedList(new ArrayList<>(opCount));
    for (int i = 0; i < opCount; i++) {
        executorService.submit(() -> operations.add(new TestMonitor(UUID.randomUUID().toString(), new ConstructionTime(), timeout)));
    }
    executorService.shutdown();
    assertTrue(executorService.awaitTermination(30, TimeUnit.SECONDS));
    assertEquals(opCount, operations.size());
    waitForOperationsToComplete(operations);
    assertEquals(opCount, MonitoringTask.instance.getFailedOperations().size());
}

91. TcpManyClientConnectionsTest#shutdownTrees()

View license
private void shutdownTrees() {
    ExecutorService c = Executors.newCachedThreadPool(new NamedThreadFactory("Tree Closer", true));
    for (int i = 0; i < MAX; i++) {
        final int j = i;
        c.execute(trees[j]::close);
    }
    c.shutdown();
    try {
        c.awaitTermination(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new AssertionError(e);
    }
}

92. ChronicleMapBuilder#establishCleanupThread()

View license
private void establishCleanupThread(ReplicatedChronicleMap map) {
    OldDeletedEntriesCleanup cleanup = new OldDeletedEntriesCleanup(map);
    NamedThreadFactory threadFactory = new NamedThreadFactory("cleanup thread for map persisted at " + map.file());
    ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);
    executor.submit(cleanup);
    map.addCloseable(cleanup);
    // WARNING this relies on the fact that ReplicatedChronicleMap closes closeables in the same
    // order as they are added, i. e. OldDeletedEntriesCleanup instance close()d before the
    // following closeable
    map.addCloseable(() -> {
        executor.shutdown();
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            LOG.error("", e);
        }
    });
}

93. Issue24ChronicleSetTest#issue24ChronicleSetTest()

View license
@Test
public void issue24ChronicleSetTest() throws IOException {
    ChronicleSet<String> set = initSet(String.class, 1_000_000, 30);
    ExecutorService executor = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 10; i++) {
        Runnable worker = new WorkerThread(set);
        executor.execute(worker);
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
    }
    System.out.println("Finished all threads");
}

94. ScriptCallableTest#testFuture()

View license
@Test
public void testFuture() throws Exception {
    JexlScript e = JEXL.createScript("while(true);");
    FutureTask<Object> future = new FutureTask<Object>(e.callable(null));
    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.submit(future);
    Object t = 42;
    try {
        t = future.get(100, TimeUnit.MILLISECONDS);
        Assert.fail("should have timed out");
    } catch (TimeoutException xtimeout) {
        future.cancel(true);
    } finally {
        executor.shutdown();
    }
    Assert.assertTrue(future.isCancelled());
    Assert.assertEquals(42, t);
}

95. ClientValueTest#runAll()

View license
private void runAll(List<SetCheckValue> runs) throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    for (SetCheckValue run : runs) {
        executorService.execute(run);
    }
    executorService.shutdown();
    long wait = 10 * DateUtils.MILLIS_PER_SECOND;
    while (wait > 0 && !executorService.awaitTermination(500, TimeUnit.MILLISECONDS)) {
        wait -= 500;
    }
    Assert.assertTrue(wait > 0);
}

96. ConcourseExecutors#executeAndAwaitTerminationAndShutdown()

Project: concourse
Source File: ConcourseExecutors.java
View license
/**
     * Create a temporary [email protected] ExecutorService} thread pool with enough
     * threads to execute [email protected] commands} and block until all the tasks have
     * completed. Afterwards, the thread pool is shutdown.
     * 
     * @param threadNamePrefix
     * @param commands
     */
public static void executeAndAwaitTerminationAndShutdown(String threadNamePrefix, Runnable... commands) {
    ExecutorService executor = Executors.newFixedThreadPool(commands.length, getThreadFactory(threadNamePrefix));
    for (Runnable command : commands) {
        executor.execute(command);
    }
    executor.shutdown();
    try {
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        throw Throwables.propagate(e);
    }
}

97. CreateTableIntegrationTest#executeCreateTableThreaded()

View license
private void executeCreateTableThreaded(final String statement) throws Throwable {
    ExecutorService executorService = Executors.newFixedThreadPool(20);
    final AtomicReference<Throwable> lastThrowable = new AtomicReference<>();
    for (int i = 0; i < 20; i++) {
        executorService.submit(new Runnable() {

            @Override
            public void run() {
                try {
                    execute(statement);
                } catch (Throwable t) {
                    lastThrowable.set(t);
                }
            }
        });
    }
    executorService.shutdown();
    assertThat("executorservice did not shutdown within timeout", executorService.awaitTermination(3, TimeUnit.SECONDS), is(true));
    Throwable throwable = lastThrowable.get();
    if (throwable != null) {
        throw throwable;
    }
}

98. ThreadsTest#normalShutdown()

Project: cyfm
Source File: ThreadsTest.java
View license
@Test
public void normalShutdown() throws InterruptedException {
    Logger logger = LoggerFactory.getLogger("test");
    LogbackListAppender appender = new LogbackListAppender();
    appender.addToLogger("test");
    // time not enough to shutdown,write error log.
    appender.clearLogs();
    ExecutorService pool = Executors.newSingleThreadExecutor();
    Runnable task = new Task(logger, 1000, 0);
    pool.execute(task);
    Threads.normalShutdown(pool, 500, TimeUnit.MILLISECONDS);
    assertThat(pool.isTerminated()).isTrue();
    assertThat(appender.getFirstMessage()).isEqualTo("InterruptedException");
}

99. PublishToKafkaIT#main()

Project: datacollector
Source File: PublishToKafkaIT.java
View license
public static void main(String[] args) {
    Properties props = new Properties();
    props.put("metadata.broker.list", "localhost:9001");
    props.put("serializer.class", "kafka.serializer.StringEncoder");
    props.put("request.required.acks", "-1");
    ProducerConfig config = new ProducerConfig(props);
    Producer<String, String> producer = new Producer<>(config);
    CountDownLatch startProducing = new CountDownLatch(1);
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(new ProducerRunnable(TOPIC, MULTIPLE_PARTITIONS, producer, startProducing, DataType.JSON, StreamingJsonParser.Mode.ARRAY_OBJECTS, -1, null));
    startProducing.countDown();
}

100. ServiceEngine#close()

Project: drill
Source File: ServiceEngine.java
View license
@Override
public void close() throws Exception {
    // this takes time so close them in parallel
    // Ideally though we fix this netty bug: https://github.com/netty/netty/issues/2545
    ExecutorService p = Executors.newFixedThreadPool(2);
    submit(p, "userServer", userServer);
    submit(p, "dataPool", dataPool);
    submit(p, "controller", controller);
    p.shutdown();
    try {
        p.awaitTermination(3, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    AutoCloseables.close(userAllocator, controlAllocator, dataAllocator);
}