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:org.hupo.psi.mi.psicquic.registry.PsicquicRegistryStatusChecker.java

@Scheduled(fixedDelay = 5 * 60 * 1000) // every 5 mins
public void refreshServices() {

    ExecutorService executorService = threadConfig.getExecutorService();

    runningTasks.clear();/*w w  w  .jav a2s.  co  m*/

    for (final ServiceType serviceStatus : config.getRegisteredServices()) {
        Runnable runnable = new Runnable() {
            public void run() {
                checkStatus(serviceStatus);
            }
        };
        runningTasks.add(executorService.submit(runnable));
    }

    checkAndResumeRegistryTasks();

    lastRefreshed = new Date();
}

From source file:fsm.series.Series_CF.java

/**
 * Computes the 5 integrals simultaneously for increased performance.
 *
 * @param m Fourier term row/*from  ww w.j  a v a  2 s.co  m*/
 * @param n Fourier term column
 * @return double array of size 5 with indexes corresponding to integral
 * number (1-5)
 */
@Override
public double[] getIntegralValues(int m, int n) {

    double[] I = new double[5];

    Callable<Double> tsk1 = () -> getI1(m, n);

    Callable<Double> tsk2 = () -> getI2(m, n);

    Callable<Double> tsk3 = () -> getI3(m, n);

    Callable<Double> tsk4 = () -> getI4(m, n);

    Callable<Double> tsk5 = () -> getI5(m, n);

    ExecutorService service;
    final Future<Double> thread1, thread2, thread3, thread4, thread5;

    service = Executors.newFixedThreadPool(5);
    thread1 = service.submit(tsk1);
    thread2 = service.submit(tsk2);
    thread3 = service.submit(tsk3);
    thread4 = service.submit(tsk4);
    thread5 = service.submit(tsk5);

    try {
        I[0] = thread1.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CF.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        I[1] = thread2.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CF.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        I[2] = thread3.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CF.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        I[3] = thread4.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CF.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        I[4] = thread5.get();
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Series_CF.class.getName()).log(Level.SEVERE, null, ex);
    }

    service.shutdownNow();

    return I;
}

From source file:com.easarrive.aws.plugins.common.service.impl.SQSNotificationService.java

/**
 * {@inheritDoc}/*from  www. j  a  v a  2 s.  c  o  m*/
 */
@Override
public List<NotificationHandleResult<Message, Boolean>> handleNotification(Message message)
        throws AWSPluginException {
    try {
        if (message == null) {
            throw new AWSPluginException("The message is null");
        }
        if (notificationHandlerList == null) {
            throw new AWSPluginException("The notificationHandlerList is null for message (ID : %s)",
                    message.getMessageId());
        }
        if (notificationHandlerList.isEmpty()) {
            throw new AWSPluginException("The notificationHandlerList is empty for message (ID : %s)",
                    message.getMessageId());
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<List<NotificationHandleResult<Message, Boolean>>>> resultList = new ArrayList<Future<List<NotificationHandleResult<Message, Boolean>>>>();
        for (INotificationHandler<Message, Boolean> notificationHandler : notificationHandlerList) {
            Future<List<NotificationHandleResult<Message, Boolean>>> future = executorService
                    .submit(new NotificationHandlerCallable(notificationHandler, message));
            resultList.add(future);
        }

        List<NotificationHandleResult<Message, Boolean>> returnList = new ArrayList<NotificationHandleResult<Message, Boolean>>();
        //??
        for (Future<List<NotificationHandleResult<Message, Boolean>>> fs : resultList) {
            try {
                List<NotificationHandleResult<Message, Boolean>> result = fs.get();
                for (NotificationHandleResult<Message, Boolean> notificationHandleResult : result) {
                    returnList.add(notificationHandleResult);
                }
            } catch (Exception e) {
                if (logger.isErrorEnabled()) {
                    logger.error(e.getMessage(), e);
                }
                returnList.add(
                        new NotificationHandleResult<Message, Boolean>(message.getMessageId(), message, false));
            } finally {
                //????????
                executorService.shutdown();
            }
        }
        return returnList;
    } catch (Exception e) {
        throw new AWSPluginException(e.getMessage(), e);
    }
}

From source file:no.ntnu.idi.socialhitchhiking.map.GeoHelper.java

/**
 * Gets a {@link JSONObject} from an address string
 * @param adr/*from   ww w. j a v  a 2s .  c om*/
 * @return
 */
private static JSONObject getLocationInfo(final String adr) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<StringBuilder> callable = new Callable<StringBuilder>() {
        @Override
        public StringBuilder call() throws ClientProtocolException, IOException {
            StringBuilder stringBuilder = new StringBuilder();
            String address;
            address = adr.replaceAll(" ", "%20");
            address = address.replaceAll("\n", "%20");
            HttpPost httppost = new HttpPost(
                    "http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            stringBuilder = new StringBuilder();

            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
            return stringBuilder;
        }
    };
    Future<StringBuilder> future = executor.submit(callable);
    StringBuilder stringBuilder;
    try {
        stringBuilder = future.get();
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        stringBuilder = new StringBuilder();
    } catch (ExecutionException e1) {
        stringBuilder = new StringBuilder();
    }
    executor.shutdown();

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObject;
}

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

private void tryChainedCountSum(int numThreads, int numEvents) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    // This should fail all test in this class
    // config.getEngineDefaults().getThreading().setInsertIntoDispatchPreserveOrder(false);

    EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();//from w w w.  j av a 2  s. c o m

    // setup statements
    EPStatement stmtInsertOne = engine.getEPAdministrator()
            .createEPL("insert into MyStreamOne select count(*) as cnt from " + SupportBean.class.getName());
    EPStatement stmtInsertTwo = engine.getEPAdministrator()
            .createEPL("insert into MyStreamTwo select sum(cnt) as mysum from MyStreamOne");
    EPStatement stmtInsertThree = engine.getEPAdministrator().createEPL("select * from MyStreamTwo");
    SupportUpdateListener listener = new SupportUpdateListener();
    stmtInsertThree.addListener(listener);

    // 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 SendEventRWLockCallable(i, sharedStartLock, engine, new GeneratorIterator(numEvents)));
    }
    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());
    }

    // assert result
    EventBean newEvents[] = listener.getNewDataListFlattened();
    for (int i = 0; i < numEvents - 1; i++) {
        long expected = total(i + 1);
        assertEquals(expected, newEvents[i].get("mysum"));
    }

    stmtInsertOne.destroy();
    stmtInsertTwo.destroy();
    stmtInsertThree.destroy();
}

From source file:com.clonescriptscrapper.crawler.CloneScriptScrapper.java

public void crawledCategories() throws URISyntaxException, IOException, InterruptedException, Exception {

    String url = "http://www.clonescriptdirectory.com/";

    //       Document doc = Jsoup.parse(fetchPage(new URI(url)));
    String response = "";
    response = new GetRequestHandler().doGetRequest(new URL(url));

    Document doc = Jsoup.parse(response);

    //        System.out.println("---" + doc);
    Elements ele = doc.select("table[class=categories] tbody tr td a");
    for (Element ele1 : ele) {

        objCategories = new Categories();

        String title = ele1.text();
        String href = ele1.attr("href");
        System.out.println("Title : " + ele1.text());
        System.out.println("Href : " + ele1.attr("href"));

        objCategories.setCategoryName(title);
        objCategories.setCategoryUrl(href);

        objCloneScriptDirectoryDaoImpl.insertCategoriesData(objCategories);
    }//from   w w w.  ja va2 s  . c  o  m

    List<Future<String>> list = new ArrayList<Future<String>>();
    ExecutorService executor = Executors.newFixedThreadPool(5);

    List<Categories> listCatogories = objCloneScriptDirectoryDaoImpl.getCategoriesDataList();

    for (Categories listCatogory : listCatogories) {

        try {
            objCloneScriptDirectoryDaoImpl.updateCategoriesData(objCategories);
            Callable worker = new CrawlingEachUrlData(listCatogory, objCloneScriptDirectoryDaoImpl);
            Future<String> future = executor.submit(worker);
            list.add(future);
        } catch (Exception exx) {
            System.out.println(exx);
        }

    }

    for (Future<String> fut : list) {
        try {
            //print the return value of Future, notice the output delay in console
            // because Future.get() waits for task to get completed
            System.out.println(new Date() + "::" + fut.get());
        } catch (InterruptedException | ExecutionException ep) {
            ep.printStackTrace();
        }
    }
    //shut down the executor service now
    executor.shutdown();

    //            objcrawlingUrlData.crawlingUrlData(href);
}

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

@Test
public void testRelease1AtATime() throws Exception {
    final int CLIENT_QTY = 10;
    final int MAX = CLIENT_QTY / 2;
    final AtomicInteger maxLeases = new AtomicInteger(0);
    final AtomicInteger activeQty = new AtomicInteger(0);
    final AtomicInteger uses = new AtomicInteger(0);

    List<Future<Object>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newFixedThreadPool(CLIENT_QTY);
    for (int i = 0; i < CLIENT_QTY; ++i) {
        Future<Object> f = service.submit(new Callable<Object>() {
            @Override//w w w  .j a  v  a  2s .  com
            public Object call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        new RetryOneTime(1));
                client.start();
                try {
                    InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX);
                    Lease lease = semaphore.acquire(10, TimeUnit.SECONDS);
                    Assert.assertNotNull(lease);
                    uses.incrementAndGet();
                    try {
                        synchronized (maxLeases) {
                            int qty = activeQty.incrementAndGet();
                            if (qty > maxLeases.get()) {
                                maxLeases.set(qty);
                            }
                        }

                        Thread.sleep(500);
                    } finally {
                        activeQty.decrementAndGet();
                        lease.close();
                    }
                } finally {
                    client.close();
                }
                return null;
            }
        });
        futures.add(f);
    }

    for (Future<Object> f : futures) {
        f.get();
    }

    Assert.assertEquals(uses.get(), CLIENT_QTY);
    Assert.assertEquals(maxLeases.get(), MAX);
}

From source file:gobblin.tunnel.TunnelTest.java

@Test
public void mustHandleMultipleConnections() throws Exception {
    mockExample();//from   w  w w .ja v  a  2  s.  c om
    Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT);
    int clients = 5;

    final CountDownLatch startSignal = new CountDownLatch(1);
    final CountDownLatch doneSignal = new CountDownLatch(clients);

    ExecutorService executor = Executors.newFixedThreadPool(clients);
    try {
        final int tunnelPort = tunnel.getPort();

        List<Future<String>> results = new ArrayList<Future<String>>();

        for (int i = 0; i < clients; i++) {
            Future<String> result = executor.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    startSignal.await();

                    try {
                        return fetchContent(tunnelPort);
                    } finally {
                        doneSignal.countDown();
                    }
                }
            });

            results.add(result);
        }

        startSignal.countDown();
        doneSignal.await();

        for (Future<String> result : results) {
            assertNotNull(result.get());
        }
    } finally {
        tunnel.close();
    }
}

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

private void trySendCountFollowedBy(int numThreads, int numEvents,
        ConfigurationEngineDefaults.Threading.Locking locking) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.getEngineDefaults().getThreading().setInsertIntoDispatchLocking(locking);
    config.getEngineDefaults().getThreading().setInsertIntoDispatchTimeout(5000); // 5 second timeout
    // This should fail all test in this class
    // config.getEngineDefaults().getThreading().setInsertIntoDispatchPreserveOrder(false);

    EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();/*from   w  ww.  ja  v a  2s . c  o  m*/

    // setup statements
    EPStatement stmtInsert = engine.getEPAdministrator()
            .createEPL("insert into MyStream select count(*) as cnt from " + SupportBean.class.getName());
    stmtInsert.addListener(new UpdateListener() {

        public void update(EventBean[] newEvents, EventBean[] oldEvents) {
            log.debug(".update cnt=" + newEvents[0].get("cnt"));
        }
    });

    SupportUpdateListener listeners[] = new SupportUpdateListener[numEvents];
    for (int i = 0; i < numEvents; i++) {
        String text = "select * from pattern [MyStream(cnt=" + (i + 1) + ") -> MyStream(cnt=" + (i + 2) + ")]";
        EPStatement stmt = engine.getEPAdministrator().createEPL(text);
        listeners[i] = new SupportUpdateListener();
        stmt.addListener(listeners[i]);
    }

    // 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 SendEventRWLockCallable(i, sharedStartLock, engine, new GeneratorIterator(numEvents)));
    }
    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());
    }

    // assert result
    for (int i = 0; i < numEvents - 1; i++) {
        assertEquals("Listener not invoked: #" + i, 1, listeners[i].getNewDataList().size());
    }
}

From source file:com.collective.celos.ci.mode.TestTask.java

private List<Future> submitTestRuns() {
    ExecutorService executor = Executors.newCachedThreadPool();
    List<Future> futures = Lists.newArrayList();
    for (final TestRun testRun : testRuns) {
        Callable callable = new Callable<Void>() {
            @Override/*from   www .  j av  a2  s.  c o  m*/
            public Void call() throws Exception {
                testRun.start();
                return null;
            }
        };
        futures.add(executor.submit(callable));
    }
    return futures;
}