Example usage for java.util.concurrent ExecutorService shutdown

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

Introduction

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

Prototype

void shutdown();

Source Link

Document

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

Usage

From source file:hivemall.mix.server.MixServerTest.java

@Test
public void test2ClientsZeroOneDenseModel() throws InterruptedException {
    final int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "30" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);//from  ww  w.  j a  va  2  s .co m

    waitForState(server, ServerState.RUNNING);

    final ExecutorService clientsExec = Executors.newCachedThreadPool();
    for (int i = 0; i < 2; i++) {
        clientsExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    invokeClient01("test2ClientsZeroOne", port, true, false);
                } catch (InterruptedException e) {
                    Assert.fail(e.getMessage());
                }
            }
        });
    }
    clientsExec.awaitTermination(30, TimeUnit.SECONDS);
    clientsExec.shutdown();
    serverExec.shutdown();
}

From source file:hivemall.mix.server.MixServerTest.java

@Test
public void test2ClientsZeroOneSparseModelWithMixCanceling() throws InterruptedException {
    final int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "30" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);//w w  w.j  av a2s.  com

    waitForState(server, ServerState.RUNNING);

    final ExecutorService clientsExec = Executors.newCachedThreadPool();
    for (int i = 0; i < 2; i++) {
        clientsExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    invokeClient01("test2ClientsZeroOne", port, false, true);
                } catch (InterruptedException e) {
                    Assert.fail(e.getMessage());
                }
            }
        });
    }
    clientsExec.awaitTermination(30, TimeUnit.SECONDS);
    clientsExec.shutdown();
    serverExec.shutdown();
}

From source file:hivemall.mix.server.MixServerTest.java

@Test
public void test2ClientsZeroOneSparseModel() throws InterruptedException {
    final int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "30" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);/*from www  . j  av  a 2s . c  om*/

    waitForState(server, ServerState.RUNNING);

    final ExecutorService clientsExec = Executors.newCachedThreadPool();
    for (int i = 0; i < 2; i++) {
        clientsExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    invokeClient01("test2ClientsZeroOne", port, false, false);
                } catch (InterruptedException e) {
                    Assert.fail(e.getMessage());
                }
            }
        });
    }
    clientsExec.awaitTermination(30, TimeUnit.SECONDS);
    clientsExec.shutdown();
    serverExec.shutdown();
}

From source file:com.emc.vipr.sync.CasMigrationTest.java

protected void delete(FPPool pool, List<String> clipIds) throws Exception {
    ExecutorService service = Executors.newFixedThreadPool(CAS_SETUP_THREADS);

    System.out.print("Deleting clips");

    for (String clipId : clipIds) {
        service.submit(new ClipDeleter(pool, clipId));
    }/*from ww  w.java 2s.  c o m*/

    service.shutdown();
    service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES);
    service.shutdownNow();

    System.out.println();
}

From source file:com.laudandjolynn.mytv.proxy.MyTvProxyManager.java

public void prepareProxies(ProxyProvider... providers) {
    int length = providers == null ? 0 : providers.length;
    if (length > 0) {
        int maxThreadNum = Constant.CPU_PROCESSOR_NUM;
        ThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("MyTv_Find_Proxies_%d")
                .build();//  w  ww  .j  ava 2 s .  c om
        ExecutorService executorService = Executors
                .newFixedThreadPool(length > maxThreadNum ? maxThreadNum : length, threadFactory);
        CompletionService<List<Proxy>> completionService = new ExecutorCompletionService<List<Proxy>>(
                executorService);
        providerList.clear();
        for (int i = 0; i < length; i++) {
            final ProxyProvider provider = providers[i];
            providerList.add(provider);
            completionService.submit(new Callable<List<Proxy>>() {

                @Override
                public List<Proxy> call() throws Exception {
                    return provider.getProxies();
                }
            });
        }
        executorService.shutdown();

        int count = 0;
        List<Proxy> resultList = new ArrayList<Proxy>();
        while (count < length) {
            try {
                Future<List<Proxy>> future = completionService.take();
                List<Proxy> proxies = future.get();
                if (proxies != null) {
                    resultList.addAll(proxies);
                }
            } catch (InterruptedException e) {
                logger.error("get proxies thread has interrupted.", e);
            } catch (ExecutionException e) {
                logger.error("get proxies thread has execution fail.", e);
            }
            count++;
        }
        resultList.add(LOCALHOST_PROXY);
        PROXY_QUEUE.clear();
        PROXY_QUEUE.addAll(resultList);
    }
}

From source file:com.linkedin.pinot.controller.helix.PinotResourceManagerTest.java

/**
 * Creates 5 threads that concurrently try to add 20 segments each, and asserts that we have
 * 100 segments in the end. Then launches 5 threads again that concurrently try to delete all segments,
 * and makes sure that we have zero segments left in the end.
 * @throws Exception/*www.j av a  2 s .  c  om*/
 */

@Test
public void testConcurrentAddingAndDeletingSegments() throws Exception {
    ExecutorService addSegmentExecutor = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 5; ++i) {
        addSegmentExecutor.execute(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 20; ++i) {
                    addOneSegment(TABLE_NAME);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        Assert.assertFalse(true, "Exception caught during sleep.");
                    }
                }
            }
        });
    }
    addSegmentExecutor.shutdown();
    while (!addSegmentExecutor.isTerminated()) {
    }

    final String offlineTableName = TableNameBuilder.OFFLINE_TABLE_NAME_BUILDER.forTable(TABLE_NAME);
    IdealState idealState = _helixAdmin.getResourceIdealState(HELIX_CLUSTER_NAME, offlineTableName);
    Assert.assertEquals(idealState.getPartitionSet().size(), 100);

    ExecutorService deleteSegmentExecutor = Executors.newFixedThreadPool(5);
    for (final String segment : idealState.getPartitionSet()) {
        deleteSegmentExecutor.execute(new Runnable() {

            @Override
            public void run() {
                deleteOneSegment(offlineTableName, segment);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Assert.assertFalse(true, "Exception caught during sleep.");
                }
            }
        });
    }
    deleteSegmentExecutor.shutdown();
    while (!deleteSegmentExecutor.isTerminated()) {
    }

    idealState = _helixAdmin.getResourceIdealState(HELIX_CLUSTER_NAME, offlineTableName);
    Assert.assertEquals(idealState.getPartitionSet().size(), 0);
}

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

/**
 * Gets a {@link JSONObject} from an address string
 * @param adr/*from   ww  w .  jav a 2s .  c  o m*/
 * @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:edu.cmu.lti.oaqa.bioasq.concept.retrieval.GoPubMedSeparateConceptRetrievalExecutor.java

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
    AbstractQuery aquery = TypeUtil.getAbstractQueries(jcas).stream().findFirst().get();
    Collection<QueryConcept> qconcepts = TypeUtil.getQueryConcepts(aquery);
    List<ConceptSearchResult> concepts = Collections.synchronizedList(new ArrayList<>());
    ExecutorService es = Executors.newCachedThreadPool();
    for (QueryConcept qconcept : qconcepts) {
        String queryString = bopQueryStringConstructor.formatQueryConcept(qconcept)
                .replaceAll("[^A-Za-z0-9_\\-\"]+", " ");
        LOG.info("Query string: {}", queryString);
        for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
            es.execute(() -> {//from  w  w w . ja  v a2  s.  c  o  m
                try {
                    concepts.addAll(
                            BioASQUtil.searchOntology(service, jcas, queryString, pages, hits, ontology));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    es.shutdown();
    try {
        if (!es.awaitTermination(timeout, TimeUnit.MINUTES)) {
            LOG.warn("Timeout occurs for one or some concept retrieval services.");
        }
    } catch (InterruptedException e) {
        throw new AnalysisEngineProcessException(e);
    }
    Map<String, List<ConceptSearchResult>> onto2concepts = concepts.stream()
            .collect(groupingBy(ConceptSearchResult::getSearchId));
    for (Map.Entry<String, List<ConceptSearchResult>> entry : onto2concepts.entrySet()) {
        List<ConceptSearchResult> results = entry.getValue();
        LOG.info("Retrieved {} concepts from {}", results.size(), entry.getKey());
        if (LOG.isDebugEnabled()) {
            results.stream().limit(10).forEach(c -> LOG.debug(" - {}", TypeUtil.toString(c)));
        }
    }
    TypeUtil.rankedSearchResultsByScore(concepts, limit).forEach(ConceptSearchResult::addToIndexes);
}

From source file:com.emc.ecs.sync.CasMigrationTest.java

protected String summarize(FPPool pool, List<String> clipIds) throws Exception {
    List<String> summaries = Collections.synchronizedList(new ArrayList<String>());

    ExecutorService service = Executors.newFixedThreadPool(CAS_THREADS);

    System.out.print("Summarizing clips");

    for (String clipId : clipIds) {
        service.submit(new ClipReader(pool, clipId, summaries));
    }//w ww.j a  va2 s .  c  om

    service.shutdown();
    service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES);
    service.shutdownNow();

    System.out.println();

    Collections.sort(summaries);
    StringBuilder out = new StringBuilder();
    for (String summary : summaries) {
        out.append(summary);
    }
    return out.toString();
}

From source file:com.emc.vipr.sync.CasMigrationTest.java

protected String summarize(FPPool pool, List<String> clipIds) throws Exception {
    List<String> summaries = Collections.synchronizedList(new ArrayList<String>());

    ExecutorService service = Executors.newFixedThreadPool(CAS_SETUP_THREADS);

    System.out.print("Summarizing clips");

    for (String clipId : clipIds) {
        service.submit(new ClipReader(pool, clipId, summaries));
    }//from w ww . j a  v  a  2 s  .  com

    service.shutdown();
    service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES);
    service.shutdownNow();

    System.out.println();

    Collections.sort(summaries);
    StringBuilder out = new StringBuilder();
    for (String summary : summaries) {
        out.append(summary);
    }
    return out.toString();
}