Example usage for java.util.concurrent ExecutorService shutdownNow

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

Introduction

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

Prototype

List<Runnable> shutdownNow();

Source Link

Document

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

Usage

From source file:com.adaptris.core.services.splitter.ServiceWorkerPool.java

public void warmup(final GenericObjectPool<Worker> objectPool) throws CoreException {
    ExecutorService populator = Executors
            .newCachedThreadPool(new ManagedThreadFactory(this.getClass().getSimpleName()));
    try {//from  w  w w  .  ja  va 2s .  co m
        log.trace("Warming up {} service-workers", maxThreads);
        final List<Future<Worker>> futures = new ArrayList<>(maxThreads);

        for (int i = 0; i < maxThreads; i++) {
            futures.add(populator.submit(new Callable<Worker>() {

                @Override
                public Worker call() throws Exception {
                    return objectPool.borrowObject();
                }

            }));
        }
        for (Worker w : waitFor(futures)) {
            objectPool.returnObject(w);
        }
        log.trace("ObjectPool contains {} (active) of {} objects", objectPool.getNumActive(),
                objectPool.getNumIdle());
    } catch (Exception e) {
        throw ExceptionHelper.wrapCoreException(e);
    } finally {
        populator.shutdownNow();
    }
}

From source file:com.legstar.host.server.PoolingTest.java

/**
 * Schedule multiple simultaneous work units.
 * @throws Exception if test fails//from   w  ww .j a  va  2 s.  c  om
 */
public void testScheduleMultipleWork() throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(CLIENT_THREADS);
    WorkManager wm = new WorkManagerImpl(executor);
    EngineHandler engHandler = new EngineHandler(getPoolingEngineConfig());
    engHandler.init();

    LegStarAddress address = new LegStarAddress("TheMainframe");
    address.setHostUserID(HOST_USERID);
    address.setHostPassword(HOST_PASSWORD);

    Client[] clients = new Client[3];
    for (int i = 0; i < clients.length; i++) {
        LegStarRequest request = new LegStarRequest("Request01", address, getLsfileaeRequestMessage());
        clients[i] = new Client(engHandler.getEngine(), "Client" + Integer.toString(i), request);
        wm.schedule(clients[i], new ClientListener());
        Thread.sleep(20L);
    }

    /* Time is needed to process these requests */
    Thread.sleep(10000L);
    engHandler.stop();
    executor.shutdownNow();

    for (int i = 0; i < clients.length; i++) {
        assertEquals(LsfileaeCases.getHostBytesHexReply100(), HostData
                .toHexString(clients[i].getRequest().getResponseMessage().getDataParts().get(0).getContent()));
    }
}

From source file:com.adaptris.core.services.splitter.ServiceWorkerPool.java

/**
 * /*  ww w .ja v  a  2s. c o m*/
 * @deprecated since 3.8.3 switch to commons-pool2 instead.
 */
@Deprecated
@Removal(version = "3.9.0", message = "use commons-pool2 variant instead")
public void warmup(final org.apache.commons.pool.impl.GenericObjectPool<Worker> objectPool)
        throws CoreException {
    logDeprecationWarning();
    ExecutorService populator = Executors
            .newCachedThreadPool(new ManagedThreadFactory(this.getClass().getSimpleName()));
    try {
        log.trace("Warming up {} service-workers", maxThreads);
        final List<Future<Worker>> futures = new ArrayList<>(maxThreads);

        for (int i = 0; i < maxThreads; i++) {
            futures.add(populator.submit(new Callable<Worker>() {

                @Override
                public Worker call() throws Exception {
                    return objectPool.borrowObject();
                }

            }));
        }
        for (Worker w : waitFor(futures)) {
            objectPool.returnObject(w);
        }
        log.trace("ObjectPool contains {} (active) of {} objects", objectPool.getNumActive(),
                objectPool.getNumIdle());

    } catch (Exception e) {
        throw ExceptionHelper.wrapCoreException(e);
    } finally {
        populator.shutdownNow();
    }
}

From source file:org.apache.hadoop.hbase.util.RegionMover.java

/**
 * Unload regions from given {@link #hostname} using ack/noAck mode and {@link #maxthreads}.In
 * noAck mode we do not make sure that region is successfully online on the target region
 * server,hence it is best effort.We do not unload regions to hostnames given in
 * {@link #excludeFile}./*from w w w .  j  ava2 s .  co  m*/
 * @return true if unloading succeeded, false otherwise
 * @throws InterruptedException if the unloader thread was interrupted
 * @throws ExecutionException
 * @throws TimeoutException
 */
public boolean unload() throws InterruptedException, ExecutionException, TimeoutException {
    setConf();
    deleteFile(this.filename);
    ExecutorService unloadPool = Executors.newFixedThreadPool(1);
    Future<Boolean> unloadTask = unloadPool.submit(new Unload(this));
    unloadPool.shutdown();
    try {
        if (!unloadPool.awaitTermination((long) this.timeout, TimeUnit.SECONDS)) {
            LOG.warn("Timed out before finishing the unloading operation. Timeout:" + this.timeout + "sec");
            unloadPool.shutdownNow();
        }
    } catch (InterruptedException e) {
        unloadPool.shutdownNow();
        Thread.currentThread().interrupt();
    }
    try {
        return unloadTask.get(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        LOG.warn("Interrupted while unloading Regions from " + this.hostname, e);
        throw e;
    } catch (ExecutionException e) {
        LOG.error("Error while unloading regions from RegionServer " + this.hostname, e);
        throw e;
    }
}

From source file:bemap.SimpleSerial.java

public int searchDevicePort() throws InterruptedException {
    String[] portNames = SerialPortList.getPortNames();
    if (SERIAL_DEBUG)
        BeMapEditor.mainWindow.append("\nFound ports: " + Arrays.toString(portNames));
    int portNumber = -1;
    for (int i = 0; i < portNames.length; i++) {

        currentPortName = portNames[i];//from www .  ja  v  a  2  s.  com

        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new PortSearchTask());

        try {
            String returnPort = future.get(3, TimeUnit.SECONDS);
            if (!"NULL".equals(returnPort)) {
                portNumber = i;
                i = portNames.length; //quit loop
            }

        } catch (ExecutionException ex) {
            Logger.getLogger(SimpleSerial.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TimeoutException ex) {
            Logger.getLogger(SimpleSerial.class.getName()).log(Level.SEVERE, null, ex);
            if (SERIAL_DEBUG)
                BeMapEditor.mainWindow.append("\nOpening port " + currentPortName + " has timed out");
        }

        executor.shutdownNow();
    }
    if (portNumber < 0) {
        deviceConnected = false;
        return 0;
    } else {
        serialPortName = portNames[portNumber];
        deviceConnected = true;
        if (SERIAL_DEBUG)
            BeMapEditor.mainWindow.append("\nDevice detected on port " + serialPortName);
        return 1; //success
    }
}

From source file:org.apache.phoenix.execute.UpsertSelectOverlappingBatchesIT.java

@Test
public void testUpsertSelectSameBatchConcurrently() throws Exception {
    try (Connection conn = driver.connect(url, props)) {
        int numUpsertSelectRunners = 5;
        ExecutorService exec = Executors.newFixedThreadPool(numUpsertSelectRunners);
        CompletionService<Boolean> completionService = new ExecutorCompletionService<Boolean>(exec);
        List<Future<Boolean>> futures = Lists.newArrayListWithExpectedSize(numUpsertSelectRunners);
        // run one UPSERT SELECT for 100 rows (that locks the rows for a long time)
        futures.add(completionService.submit(new UpsertSelectRunner(dataTable, 0, 105, 1)));
        // run four UPSERT SELECTS for 5 rows (that overlap with slow running UPSERT SELECT)
        for (int i = 0; i < 100; i += 25) {
            futures.add(completionService.submit(new UpsertSelectRunner(dataTable, i, i + 25, 5)));
        }/*from w  w  w .jav a  2 s  . co m*/
        int received = 0;
        while (received < futures.size()) {
            Future<Boolean> resultFuture = completionService.take();
            Boolean result = resultFuture.get();
            received++;
            assertTrue(result);
        }
        exec.shutdownNow();
    }
}

From source file:gr.demokritos.iit.cru.creativity.reasoning.semantic.WebMiner.java

public static String WebMiner(String seed, int difficulty, String language, boolean compactForm)
        throws ClassNotFoundException, SQLException, IOException, InstantiationException,
        IllegalAccessException {/*w w  w . j  a va2s.c o m*/
    Gson gson = new Gson();
    Connect c = new Connect(language);
    RandomWordGenerator r = new RandomWordGenerator(c);
    String randomPhrase = r.selectRandomWord(seed, difficulty).replace(",", " ");
    InfoSummarization inf = new InfoSummarization(c);
    LinkedHashMap<String, Double> TagCloud = new LinkedHashMap<String, Double>();

    Set<String> pages = new HashSet<String>();
    ArrayList<String> urls = new ArrayList<String>();
    ArrayList<String> urls_temp = new ArrayList<String>();
    if (language.equalsIgnoreCase("en")) {
        if (randomPhrase.length() == 0) {
            randomPhrase = seed;
        }
        String bingAppId = c.getBingAppId();
        BingCrawler bc = new BingCrawler(bingAppId, language);
        urls_temp = bc.crawl(randomPhrase);
        int url_loop = 0;
        while ((url_loop < 5) && (url_loop < urls_temp.size())) {
            urls.add(urls_temp.get(url_loop));
            url_loop++;
        }
    } else if (language.equalsIgnoreCase("el")) {
        String bingAppId = c.getBingAppId();
        BingCrawler bc = new BingCrawler(bingAppId, language);
        urls_temp = bc.crawl(randomPhrase);
        int url_loop = 0;
        while ((url_loop < 5) && (url_loop < urls_temp.size())) {
            urls.add(urls_temp.get(url_loop));
            url_loop++;
        }
    } else if (language.equalsIgnoreCase("de")) {//keep only the first word of the random phrase for search
        if (randomPhrase.length() == 0) {
            randomPhrase = seed;
        }
        urls_temp = HTMLUtilities.linkExtractor(
                "http://www.fragfinn.de/kinderliste/suche?start=0&query=" + randomPhrase.split(" ")[0], "UTF-8",
                0);

        for (String url : urls_temp) {
            urls.add(StringEscapeUtils.unescapeHtml4(url));
            if (urls.size() == 5) {
                break;
            }
        }
    }
    String delims = "[{} .,;?!():\"]+";

    String[] words = randomPhrase.split(",");
    String[] user_keywords = seed.split(delims);
    if (urls.size() > 0) {
        ExecutorService threadPool = Executors.newFixedThreadPool(urls.size());
        for (String url : urls) {
            threadPool.submit(new HTMLPages(url, pages, language)); //stopWordSet, tokensHashMap,language));
            // threadPool.submit(HTMLTokenizer());
        }
        threadPool.shutdown();
        while (!threadPool.isTerminated()) {

        }

        LinkedHashMap<ArrayList<String>, Double> temp = inf.TopTermsBing(pages, compactForm);
        HashMap<String, Double> temp2 = new HashMap<String, Double>();
        for (ArrayList<String> stems : temp.keySet()) {
            for (int j = 0; j < stems.size(); j++) {
                String s = stems.get(j).split("\\{")[0];
                s = s.replace(",", " ");
                s = s.trim();

                boolean wordnet = true;
                //if term is not one of the initial random phrase
                for (int i = 0; i < words.length; i++) {
                    if (s.equalsIgnoreCase(words[i])) {
                        wordnet = false;
                    }
                }
                //and if it 's not in the initial words of user
                for (int i = 0; i < user_keywords.length; i++) {
                    if (s.equalsIgnoreCase(user_keywords[i])) {
                        wordnet = false;
                    }
                }
                //in german or greek, ignore english words from search english words
                if (language.equalsIgnoreCase("de") || language.equalsIgnoreCase("el")) {
                    if (c.getWn().getCommonPos(s) != null) {
                        continue;
                    }
                }
                //return it with its stem's weight
                if (wordnet) {
                    //for every stem, put each of its corresponding terms to tagCloud with the stem's tf
                    temp2.put(stems.get(j), temp.get(stems));
                }
            }
        }
        TagCloud = inf.sortHashMapByValues(temp2);
        threadPool.shutdownNow();
    }
    String json = gson.toJson(TagCloud);
    c.CloseConnection();
    return json;
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpResponse executeWithTimeout(final HttpMethodBase httpMethod, int timeoutMillis) {
    client.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false));
    ExecutorService service = Executors.newSingleThreadExecutor();

    Future<HttpResponse> future = service.submit(new Callable<HttpResponse>() {
        @Override//from   w  w w  .  j  av  a  2s  . co m
        public HttpResponse call() throws IOException {
            return execute(httpMethod);
        }
    });

    try {
        return future.get(timeoutMillis, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        String uriInfo = "";
        try {
            uriInfo = " for " + httpMethod.getURI();
        } catch (Exception ie) {
        }
        LOG.warn("Http connection thread was interrupted or has timed out" + uriInfo, e);
        return new HttpResponse(HttpStatus.SC_REQUEST_TIMEOUT, "Request Timeout", null);
    } finally {
        service.shutdownNow();
    }
}

From source file:com.aerospike.benchmarks.Main.java

private void doInserts(AerospikeClient client) throws Exception {
    ExecutorService es = Executors.newFixedThreadPool(this.nThreads);

    // Create N insert tasks
    int ntasks = this.nThreads < this.nKeys ? this.nThreads : this.nKeys;
    int start = this.startKey;
    int keysPerTask = this.nKeys / ntasks + 1;

    for (int i = 0; i < ntasks; i++) {
        InsertTask it = new InsertTaskSync(client, args, counters, start, keysPerTask);
        es.execute(it);/*from  ww w .  j  a  v a2 s  .co m*/
        start += keysPerTask;
    }
    collectInsertStats();
    es.shutdownNow();
}

From source file:com.aerospike.benchmarks.Main.java

private void doAsyncInserts(AsyncClient client) throws Exception {
    ExecutorService es = Executors.newFixedThreadPool(this.nThreads);

    // Create N insert tasks
    int ntasks = this.nThreads < this.nKeys ? this.nThreads : this.nKeys;
    int start = this.startKey;
    int keysPerTask = this.nKeys / ntasks + 1;

    for (int i = 0; i < ntasks; i++) {
        InsertTask it = new InsertTaskAsync(client, args, counters, start, keysPerTask);
        es.execute(it);/*from  ww w .  j a  va2  s . c  om*/
        start += keysPerTask;
    }
    collectInsertStats();
    es.shutdownNow();
}