Example usage for java.util.concurrent ExecutorCompletionService take

List of usage examples for java.util.concurrent ExecutorCompletionService take

Introduction

In this page you can find the example usage for java.util.concurrent ExecutorCompletionService take.

Prototype

public Future<V> take() throws InterruptedException 

Source Link

Usage

From source file:MyResult.java

public static void main(String[] args) throws Exception {
    // Get an executor with three threads in its thread pool
    ExecutorService exec = Executors.newFixedThreadPool(3);

    // Completed task returns an object of the TaskResult class
    ExecutorCompletionService<MyResult> completionService = new ExecutorCompletionService<>(exec);
    for (int i = 1; i <= 5; i++) {
        SleepingTask task = new SleepingTask(i, 3);
        completionService.submit(task);/* w w w .j ava2  s. c o  m*/
    }
    for (int i = 1; i <= 5; i++) {
        Future<MyResult> completedTask = completionService.take();
        MyResult result = completedTask.get();
        System.out.println("Completed a  task - " + result);
    }
    exec.shutdown();
}

From source file:gov.nih.nci.integration.caaers.invoker.CaAERSServiceInvocationStrategyFactory.java

private static synchronized void init(final String[] caaersLibLocation, final String... caaersConfig) {
    final ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(
            Executors.newSingleThreadExecutor());

    ecs.submit(new Callable<Boolean>() {

        @Override// w  w  w. j a  v a2s  . com
        public Boolean call() throws MalformedURLException, BeansException {
            final CustomClasspathXmlApplicationContext ctx = new CustomClasspathXmlApplicationContext(
                    caaersLibLocation, caaersConfig);
            caaersRegistrationServiceInvocationStrategy = (ServiceInvocationStrategy) ctx
                    .getBean("caAersRegistrationServiceInvocationStrategy");
            caaersUpdateRegistrationServiceInvocationStrategy = (ServiceInvocationStrategy) ctx
                    .getBean("caAersUpdateRegistrationServiceInvocationStrategy");
            caaersAdverseEventServiceInvocationStrategy = (ServiceInvocationStrategy) ctx
                    .getBean("caAersAdverseEventServiceInvocationStrategy");
            return Boolean.TRUE;
        }
    });

    try {
        initStatus = ecs.take().get();
        // CHECKSTYLE:OFF
    } catch (Exception e) { // NOPMD
        LOG.error("CaAERSServiceInvocationStrategyFactory.Exception inside init(). ", e);
        initStatus = Boolean.FALSE;
    }
}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * Helper function./*ww  w .  j  a  v  a 2  s  .  c  o m*/
 *
 * @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 (int i = 0; i <= threads; i++) { // create and start threads
        ecs.submit(new ThreadTesterUtil(startSignal, doneSignal, cpds, workDelay, doPreparedStatement));
    }

    startSignal.countDown(); // START TEST!
    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;
}

From source file:org.apache.solr.client.solrj.impl.BackupRequestLBHttpSolrServer.java

private RequestTaskState getResponseIfReady(ExecutorCompletionService<RequestTaskState> executer,
        boolean waitUntilTaskComplete) throws SolrException {

    Future<RequestTaskState> taskInProgress = null;
    try {//  w ww . java  2 s .co  m
        if (waitUntilTaskComplete) {
            taskInProgress = executer.take();
        } else {
            taskInProgress = executer.poll(backUpRequestDelay, TimeUnit.MILLISECONDS);
        }
        // could be null if poll time exceeded in which case return null.
        if (taskInProgress != null && !taskInProgress.isCancelled()) {
            RequestTaskState resp = taskInProgress.get();
            return resp;
        }
    } catch (InterruptedException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    } catch (ExecutionException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    }
    return null;
}

From source file:com.teradata.benchto.driver.jdbc.ConnectionPoolTest.java

private void openGivenConnectionsAmountSimultaneously(String dataSourceName, int connectionsCount)
        throws SQLException, InterruptedException, TimeoutException {
    ExecutorService executorService = newFixedThreadPool(connectionsCount);
    ExecutorCompletionService<?> completionService = new ExecutorCompletionService(executorService);
    CountDownLatch countDownLatch = new CountDownLatch(connectionsCount);
    DataSource dataSource = applicationContext.getBean(dataSourceName, DataSource.class);

    range(0, connectionsCount).mapToObj(i -> createQueryRunnable(dataSource, countDownLatch))
            .forEach(completionService::submit);

    try {/*from w w  w  .  j  a va2  s. com*/
        for (int i = 0; i < connectionsCount; i++) {
            try {
                Future<?> future = completionService.take();
                future.get(1, MINUTES);
            } catch (ExecutionException e) {
                rethrowException(e.getCause());
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        executorService.shutdownNow();
        executorService.awaitTermination(1, MINUTES);
    }
}

From source file:org.apache.solr.client.solrj.impl.BackupRequestLBHttpSolrClient.java

private RequestTaskState getResponseIfReady(ExecutorCompletionService<RequestTaskState> executer,
        int backupDelay) throws SolrException {

    Future<RequestTaskState> taskInProgress = null;
    try {/*from  w  w w. j av a2s. com*/
        if (backupDelay < 0) {
            taskInProgress = executer.take();
        } else {
            taskInProgress = executer.poll(backupDelay, TimeUnit.MILLISECONDS);
        }
        // could be null if poll time exceeded in which case return null.
        if (taskInProgress != null && !taskInProgress.isCancelled()) {
            RequestTaskState resp = taskInProgress.get();

            return resp;
        }
    } catch (InterruptedException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    } catch (ExecutionException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
    }
    return null;

}

From source file:com.alibaba.otter.shared.communication.core.impl.DefaultCommunicationClientImpl.java

public Object call(final String[] addrs, final Event event) {
    Assert.notNull(this.factory, "No factory specified");
    if (addrs == null || addrs.length == 0) {
        throw new IllegalArgumentException("addrs example: 127.0.0.1:1099");
    }/*from w  ww.j  a  va2  s .  c  o  m*/

    ExecutorCompletionService completionService = new ExecutorCompletionService(executor);
    List<Future<Object>> futures = new ArrayList<Future<Object>>(addrs.length);
    List result = new ArrayList(10);
    for (final String addr : addrs) {
        futures.add(completionService.submit((new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                return DefaultCommunicationClientImpl.this.call(addr, event);
            }
        })));
    }

    Exception ex = null;
    int errorIndex = 0;
    while (errorIndex < futures.size()) {
        try {
            Future future = completionService.take();// ?
            future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            ex = e;
            break;
        } catch (ExecutionException e) {
            ex = e;
            break;
        }

        errorIndex++;
    }

    if (errorIndex < futures.size()) {
        for (int index = 0; index < futures.size(); index++) {
            Future<Object> future = futures.get(index);
            if (future.isDone() == false) {
                future.cancel(true);
            }
        }
    } else {
        for (int index = 0; index < futures.size(); index++) {
            Future<Object> future = futures.get(index);
            try {
                result.add(future.get());
            } catch (InterruptedException e) {
                // ignore
                Thread.currentThread().interrupt();
            } catch (ExecutionException e) {
                // ignore
            }
        }
    }

    if (ex != null) {
        throw new CommunicationException(
                String.format("call addr[%s] error by %s", addrs[errorIndex], ex.getMessage()), ex);
    } else {
        return result;
    }
}

From source file:com.alibaba.otter.manager.biz.monitor.impl.GlobalMonitor.java

private void concurrentProcess(Map<Long, List<AlarmRule>> rules) {
    ExecutorCompletionService completionExecutor = new ExecutorCompletionService(executor);
    List<Future> futures = new ArrayList<Future>();
    for (Entry<Long, List<AlarmRule>> entry : rules.entrySet()) {
        final List<AlarmRule> alarmRules = entry.getValue();
        futures.add(completionExecutor.submit(new Callable<Object>() {

            @Override/*from ww  w  .java2s . c  o  m*/
            public Object call() throws Exception {
                pipelineMonitor.explore(alarmRules);
                return null;
            }
        }));
    }

    List<Throwable> exceptions = new ArrayList<Throwable>();
    int index = 0;
    int size = futures.size();
    while (index < size) {
        try {
            Future<?> future = completionExecutor.take();
            future.get();
        } catch (InterruptedException e) {
            exceptions.add(e);
        } catch (ExecutionException e) {
            exceptions.add(e);
        }
        index++;
    }

    if (!exceptions.isEmpty()) {
        StringBuilder sb = new StringBuilder(exceptions.size() + " exception happens in global monitor\n");
        sb.append("exception stack start :\n");
        for (Throwable t : exceptions) {
            sb.append(ExceptionUtils.getStackTrace(t));
        }
        sb.append("exception stack end \n");
        throw new IllegalStateException(sb.toString());
    }
}

From source file:com.alibaba.otter.manager.biz.monitor.impl.GlobalMonitor.java

private void concurrentProcess(List<Long> channelIds) {
    ExecutorCompletionService completionExecutor = new ExecutorCompletionService(executor);
    List<Future> futures = new ArrayList<Future>();
    for (final Long channelId : channelIds) {
        futures.add(completionExecutor.submit(new Callable<Object>() {

            @Override/*from  w w w  .  j  av a  2s  . c o  m*/
            public Object call() throws Exception {
                ChannelStatus status = arbitrateManageService.channelEvent().status(channelId);
                if (status.isPause()) {
                    restartAlarmRecovery.recovery(channelId);
                }
                return null;
            }
        }));
    }

    List<Throwable> exceptions = new ArrayList<Throwable>();
    int index = 0;
    int size = futures.size();
    while (index < size) {
        try {
            Future<?> future = completionExecutor.take();
            future.get();
        } catch (InterruptedException e) {
            exceptions.add(e);
        } catch (ExecutionException e) {
            exceptions.add(e);
        }
        index++;
    }

    if (!exceptions.isEmpty()) {
        StringBuilder sb = new StringBuilder(exceptions.size() + " exception happens in global monitor\n");
        sb.append("exception stack start :\n");
        for (Throwable t : exceptions) {
            sb.append(ExceptionUtils.getStackTrace(t));
        }
        sb.append("exception stack end \n");
        throw new IllegalStateException(sb.toString());
    }
}

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

@Test
public void testWaitingProcessKilledServer() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    try {//from   ww  w  . j  a  va  2 s . c o  m
        client.start();

        final CountDownLatch latch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);

        final AtomicBoolean isFirst = new AtomicBoolean(true);
        ExecutorCompletionService<Object> service = new ExecutorCompletionService<Object>(
                Executors.newFixedThreadPool(2));
        for (int i = 0; i < 2; ++i) {
            service.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    InterProcessLock lock = makeLock(client);
                    lock.acquire();
                    try {
                        if (isFirst.compareAndSet(true, false)) {
                            timing.sleepABit();

                            server.stop();
                            Assert.assertTrue(timing.awaitLatch(latch));
                            server = new TestingServer(server.getPort(), server.getTempDirectory());
                        }
                    } finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                            // ignore
                        }
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < 2; ++i) {
            service.take().get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS);
        }
    } finally {
        IOUtils.closeQuietly(client);
    }
}