Example usage for java.util.concurrent ExecutorService submit

List of usage examples for java.util.concurrent ExecutorService submit

Introduction

In this page you can find the example usage for java.util.concurrent ExecutorService submit.

Prototype

Future<?> submit(Runnable task);

Source Link

Document

Submits a Runnable task for execution and returns a Future representing that task.

Usage

From source file:com.iselect.kernal.geo.service.GeographicServiceImpl.java

@Override
public List<Future> importGeos(List<CountryDto> countries) {
    ExecutorService pools = Executors.newFixedThreadPool(2);
    List<Future> results = new ArrayList<>(countries.size());
    for (CountryDto country : countries) {
        Future result = pools.submit(new GeographicCallable(country));
        results.add(result);/*w w w. ja  v  a 2  s  .  com*/
    }
    try {
        pools.awaitTermination(1, TimeUnit.MINUTES);
        pools.shutdown();
    } catch (InterruptedException ex) {
        Logger.getLogger(GeographicServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return results;
}

From source file:org.jboss.as.test.clustering.cluster.web.ClusteredWebSimpleTestCase.java

private void abstractGracefulServe(URL baseURL1, boolean undeployOnly) throws Exception {

    final DefaultHttpClient client = HttpClientUtils.relaxedCookieHttpClient();
    String url1 = baseURL1.toString() + "simple";

    // Make sure a normal request will succeed
    HttpResponse response = client.execute(new HttpGet(url1));
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    response.getEntity().getContent().close();

    // Send a long request - in parallel
    String longRunningUrl = url1 + "?" + SimpleServlet.REQUEST_DURATION_PARAM + "=" + REQUEST_DURATION;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<HttpResponse> future = executor.submit(new RequestTask(client, longRunningUrl));

    // Make sure long request has started
    Thread.sleep(1000);//from w  w w .  j  av a  2s .co  m

    if (undeployOnly) {
        // Undeploy the app only.
        undeploy(DEPLOYMENT_1);
    } else {
        // Shutdown server.
        stop(CONTAINER_1);
    }

    // Get result of long request
    // This request should succeed since it initiated before server shutdown
    try {
        response = future.get();
        Assert.assertEquals("Request should succeed since it initiated before undeply or shutdown.",
                HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        response.getEntity().getContent().close();
    } catch (ExecutionException e) {
        e.printStackTrace(System.err);
        Assert.fail(e.getCause().getMessage());
    }

    if (undeployOnly) {
        // If we are only undeploying, then subsequent requests should return 404.
        response = client.execute(new HttpGet(url1));
        Assert.assertEquals("If we are only undeploying, then subsequent requests should return 404.",
                HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
        response.getEntity().getContent().close();
    }
}

From source file:org.jboss.as.test.clustering.cluster.web.DistributableTestCase.java

private void testGracefulServe(URL baseURL, Lifecycle lifecycle)
        throws URISyntaxException, IOException, InterruptedException {

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        URI uri = SimpleServlet.createURI(baseURL);

        // Make sure a normal request will succeed
        HttpResponse response = client.execute(new HttpGet(uri));
        try {//from  w  ww  . ja  v  a2  s .c o m
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Send a long request - in parallel
        URI longRunningURI = SimpleServlet.createURI(baseURL, REQUEST_DURATION);
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<HttpResponse> future = executor.submit(new RequestTask(client, longRunningURI));

        // Make sure long request has started
        Thread.sleep(1000);

        lifecycle.stop(NODE_1);

        // Get result of long request
        // This request should succeed since it initiated before server shutdown
        try {
            response = future.get();
            try {
                Assert.assertEquals("Request should succeed since it initiated before undeply or shutdown.",
                        HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            } finally {
                HttpClientUtils.closeQuietly(response);
            }
        } catch (ExecutionException e) {
            e.printStackTrace(System.err);
            Assert.fail(e.getCause().getMessage());
        }
    }
}

From source file:com.espertech.esper.multithread.TestMTIsolation.java

private void tryIsolated(int numThreads, int numLoops) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.getEngineDefaults().getViewResources().setShareViews(false);
    config.addEventType("SupportBean", SupportBean.class);
    EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();/*from w  ww  .  jav  a2  s .c o m*/

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future future[] = new Future[numThreads];
    ReentrantReadWriteLock sharedStartLock = new ReentrantReadWriteLock();
    sharedStartLock.writeLock().lock();
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(new IsolateUnisolateCallable(i, engine, numLoops));
    }
    Thread.sleep(100);
    sharedStartLock.writeLock().unlock();

    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);

    for (int i = 0; i < numThreads; i++) {
        assertTrue((Boolean) future[i].get());
    }
}

From source file:org.apache.mina.springrpc.example.gettingstarted.AbstractHelloServiceClientTests.java

private void executeUseConcurrent(List<Callable<HelloResponse>> tasks) {
    ExecutorService executor = Executors.newFixedThreadPool(CONCURRENT_SIZE);
    List<Future<HelloResponse>> futures = new ArrayList<Future<HelloResponse>>(RUN_TIMES);

    for (Callable<HelloResponse> task : tasks) {
        Future<HelloResponse> future = executor.submit(task);
        futures.add(future);//from www. jav  a  2 s  . c  o  m
    }
    for (Future<HelloResponse> future : futures) {
        try {
            future.get(1000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            continue;
        }
    }

    logger.info("Successful task count : " + counter.get());
}

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java

@Test
public void testBasic() throws Exception {
    final Timing timing = new Timing();
    final List<Closeable> closeables = Lists.newArrayList();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    try {/*from   w  w w .java  2s . c o m*/
        closeables.add(client);
        client.start();

        final CountDownLatch postEnterLatch = new CountDownLatch(QTY);
        final CountDownLatch postLeaveLatch = new CountDownLatch(QTY);
        final AtomicInteger count = new AtomicInteger(0);
        final AtomicInteger max = new AtomicInteger(0);
        List<Future<Void>> futures = Lists.newArrayList();
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < QTY; ++i) {
            Future<Void> future = service.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY);

                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));

                    synchronized (TestDistributedDoubleBarrier.this) {
                        int thisCount = count.incrementAndGet();
                        if (thisCount > max.get()) {
                            max.set(thisCount);
                        }
                    }

                    postEnterLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));

                    Assert.assertEquals(count.get(), QTY);

                    Assert.assertTrue(barrier.leave(10, TimeUnit.SECONDS));
                    count.decrementAndGet();

                    postLeaveLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postLeaveLatch));

                    return null;
                }
            });
            futures.add(future);
        }

        for (Future<Void> f : futures) {
            f.get();
        }
        Assert.assertEquals(count.get(), 0);
        Assert.assertEquals(max.get(), QTY);
    } finally {
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java

@Test
public void testGetParticipantNodes() throws Exception {
    final int READERS = 20;
    final int WRITERS = 8;

    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {// www. j a v a 2 s . c o  m
        client.start();

        final CountDownLatch latch = new CountDownLatch(READERS + WRITERS);
        final CountDownLatch readLatch = new CountDownLatch(READERS);
        final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock");

        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < READERS; ++i) {
            service.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    lock.readLock().acquire();
                    latch.countDown();
                    readLatch.countDown();
                    return null;
                }
            });
        }
        for (int i = 0; i < WRITERS; ++i) {
            service.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Assert.assertTrue(readLatch.await(10, TimeUnit.SECONDS));
                    latch.countDown(); // must be before as there can only be one writer
                    lock.writeLock().acquire();
                    return null;
                }
            });
        }

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

        Collection<String> readers = lock.readLock().getParticipantNodes();
        Collection<String> writers = lock.writeLock().getParticipantNodes();

        Assert.assertEquals(readers.size(), READERS);
        Assert.assertEquals(writers.size(), WRITERS);
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.netflix.curator.framework.recipes.cache.TestNodeCache.java

@Test
public void testRebuildAgainstOtherProcesses() throws Exception {
    NodeCache cache = null;//  w w w .  j  av  a  2 s.  c om
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    client.start();
    try {
        client.create().forPath("/test");
        client.create().forPath("/test/snafu", "original".getBytes());

        final CountDownLatch latch = new CountDownLatch(1);
        cache = new NodeCache(client, "/test/snafu");
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                latch.countDown();
            }
        });
        cache.rebuildTestExchanger = new Exchanger<Object>();

        ExecutorService service = Executors.newSingleThreadExecutor();
        final NodeCache finalCache = cache;
        Future<Object> future = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS);

                // simulate another process updating the node while we're rebuilding
                client.setData().forPath("/test/snafu", "other".getBytes());

                ChildData currentData = finalCache.getCurrentData();
                Assert.assertNotNull(currentData);

                finalCache.rebuildTestExchanger.exchange(new Object(), 10, TimeUnit.SECONDS);

                return null;
            }
        });
        cache.start(false);
        future.get();

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertNotNull(cache.getCurrentData());
        Assert.assertEquals(cache.getCurrentData().getData(), "other".getBytes());
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
    }
}

From source file:aos.camel.JavaFutureTest.java

@Test
public void testFutureWithoutDone() throws Exception {
    // this is the task we want to execute async
    // usually the task is something that takes
    // some time to do
    Callable<String> task = new Callable<String>() {
        public String call() throws Exception {
            // do something that takes some time
            LOG.info("Starting to process task");
            Thread.sleep(5000);//from w  ww. j  a va 2  s  .  co m
            LOG.info("Task is now done");
            return "Camel rocks";
        }
    };

    // this is the thread pool we will use
    ExecutorService executor = Executors.newCachedThreadPool();

    // now submit the task to the thread pool
    // and get the Future handle back so we can later get the result
    LOG.info("Submitting task to ExecutorService");
    Future<String> future = executor.submit(task);
    LOG.info("Task submitted and we got a Future handle");

    // instead of testing when we are done we can just get
    // the result and it will automatic wait until the task is done
    String answer = future.get();
    LOG.info("The answer is: " + answer);
}

From source file:com.seajas.search.codex.service.task.ExpirationNotifierTask.java

/**
 * Send out the actual notification e-mails.
 *///from   ww w . j  av  a2s  .c o  m
public void send() {
    if (Boolean.getBoolean("com.seajas.search.codex.notifications.disabled")) {
        logger.info(
                "Notifications have been explicitly disabled using 'com.seajas.search.codex.notifications.disabled=true'. Skipping notification expiration checks.");

        return;
    }

    logger.info("Started expiration notifier task");

    // Also use a regular date for reference, to pass to the search engine

    final Date currentDate = new Date();

    // Retrieve the list of profile profiles to attend to

    List<Identity> identities = codexService.getNotifiableIdentities(currentDate);

    if (identities.size() == 0) {
        logger.info("No notifiable identities found - finishing expiration notifier task");

        return;
    }

    // Now process the profiles using a thread-pool of at most threadMaximum threads

    ExecutorService threadPool = Executors.newFixedThreadPool(Math.min(identities.size(), threadMaximum));

    for (final Identity identity : identities)
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                List<IdentityAccount> accounts = codexService.getNotifiableAccounts(currentDate,
                        identity.getAccounts());

                for (IdentityAccount account : accounts) {
                    // Retrieve the most recently expired unreported token

                    IdentityAccountToken relevantToken = null;

                    for (IdentityAccountToken token : account.getTokens())
                        if (token.getExpireTime() > currentDate.getTime() && !token.getIsReported()) {
                            relevantToken = token;

                            break;
                        }

                    if (relevantToken == null) {
                        logger.error(
                                "No relevant token could be found - despite this account having been found to be notifiable");

                        break;
                    }

                    // Take the subject in the given language, or resort to the default language if it doesn't exist (yet)

                    String subject = null;

                    try {
                        subject = messageSource.getMessage("mail.result.subject.token.expired", null,
                                new Locale(identity.getNotifierLanguage()));
                    } catch (NoSuchMessageException e) {
                        logger.warn("Could not retrieve results message subject header in language "
                                + identity.getNotifierLanguage() + ", resorting to the default language "
                                + codexService.getDefaultApplicationLanguage());

                        subject = messageSource.getMessage("mail.confirmation.subject", null,
                                new Locale(codexService.getDefaultApplicationLanguage()));
                    }

                    // And send out the actual e-mail

                    if (!mailService.sendMessage(identity.getNotifierEmail(), subject, "TODO"))
                        logger.error(
                                "Could not e-mail the notification expiration message - attender failed to send message.");

                    // Update the processed subscribers' lastNotification indicator

                    codexService.markAccountNotified(account);
                }
            }
        });

    logger.info("Finishing expiration notifier task");
}