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:org.broadinstitute.gatk.utils.fasta.CachingIndexedFastaSequenceFileUnitTest.java

@Test(dataProvider = "ParallelFastaTest", enabled = true && !DEBUG, timeOut = 60000)
public void testCachingIndexedFastaReaderParallel(final File fasta, final int cacheSize, final int querySize,
        final int nt) throws FileNotFoundException, InterruptedException {
    final CachingIndexedFastaSequenceFile caching = new CachingIndexedFastaSequenceFile(fasta,
            getCacheSize(cacheSize), true, false);

    logger.warn(String.format("Parallel caching index fasta reader test cacheSize %d querySize %d nt %d",
            caching.getCacheSize(), querySize, nt));
    for (int iterations = 0; iterations < 1; iterations++) {
        final ExecutorService executor = Executors.newFixedThreadPool(nt);
        final Collection<Callable<Object>> tasks = new ArrayList<Callable<Object>>(nt);
        for (int i = 0; i < nt; i++)
            tasks.add(new Callable<Object>() {
                @Override//from w  ww.  j a va 2s .c  o m
                public Object call() throws Exception {
                    testSequential(caching, fasta, querySize);
                    return null;
                }
            });
        executor.invokeAll(tasks);
        executor.shutdownNow();
    }
}

From source file:org.j2free.config.ConfigurationListener.java

/**
 *
 * @param event//from   w ww  .  j ava  2s .  c  om
 */
public synchronized void contextDestroyed(ServletContextEvent event) {
    // Remove all properties from the ServletContext that were set in the
    // previous configuration.
    for (String key : loadedConfigPropKeys)
        context.removeAttribute(key);

    loadedConfigPropKeys.clear();

    // Clear resources
    Global.clear();

    if (SimpleEmailService.isEnabled()) {
        log.info("Shutting down SimpleEmailService...");
        boolean emailOff = false;
        try {
            emailOff = SimpleEmailService.shutdown(2, TimeUnit.SECONDS);
        } catch (InterruptedException ie) {
        }

        if (!emailOff)
            SimpleEmailService.shutdown();
    }

    if (SimpleHttpService.isEnabled()) {
        log.info("Shutting down SimpleHttpService...");
        boolean httpOff = false;
        try {
            httpOff = SimpleHttpService.shutdown(2, TimeUnit.SECONDS);
        } catch (InterruptedException ie) {
        }

        if (!httpOff)
            SimpleHttpService.shutdown();
    }

    ExecutorService taskExecutor = (ExecutorService) Global.get(CONTEXT_ATTR_TASK_MANAGER);
    if (taskExecutor != null) {
        log.info("Shutting down ExecutorService...");
        List<Runnable> cancelledTasks = taskExecutor.shutdownNow();
        if (cancelledTasks != null && !cancelledTasks.isEmpty()) {
            for (Runnable task : cancelledTasks) {
                log.warn("Cancelled task: " + task);
            }
        }
    }

    if (FragmentCacheTag.isEnabled()) {
        log.info("Destroying FragmentCache");
        FragmentCacheTag.disable();
    }
}

From source file:org.volkszaehler.android.JsonController.java

/**
 * A method that will execute a UrlConnect thread in the
 * given executionTime read from the globalStorage
 * @param urlConnect UrlConnect Instance that will be executed
 */// w  ww.  j  a v  a  2s .c  om
private void executeUrlConnect(UrlConnect urlConnect) {
    converter = null; // Delete old data
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<?> future = executor.submit(urlConnect);
    try {
        // wait for task to complete
        int timer = globalStorage.getExecutionTime();
        future.get(timer, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        errorMessage = "Timeout Exception";
    } catch (InterruptedException e) {
        errorMessage = "Interrupted Exception";
    } catch (ExecutionException e) {
        errorMessage = "Execution Exception";
    } finally {
        executor.shutdownNow(); // cleanup
    }
}

From source file:com.mikebl71.android.websms.connector.cabbage.CabbageConnector.java

/**
 * Called to update balance. Updates subconnector's balances concurrently.
 *///  w w w.j a  va  2s .c o m
@Override
protected void doUpdate(final Context context, final Intent intent) {
    final ConnectorSpec cs = this.getSpec(context);
    final int subCount = cs.getSubConnectorCount();
    final SubConnectorSpec[] subs = cs.getSubConnectors();

    final List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(subCount);
    for (SubConnectorSpec sub : subs) {
        final String subId = sub.getID();

        tasks.add(new Callable<Void>() {
            public Void call() throws Exception {
                // clone intent and assign it to this sub connector
                final Intent subIntent = new Intent(intent);
                ConnectorCommand cmd = new ConnectorCommand(subIntent);
                cmd.setSelectedSubConnector(subId);
                cmd.setToIntent(subIntent);
                // update balance for this subconnector
                sendData(context, new ConnectorCommand(subIntent));
                return null;
            }
        });
    }

    try {
        final ExecutorService executor = Executors.newFixedThreadPool(subCount);
        // execute all updates in parallel and wait till all are complete
        final List<Future<Void>> results = executor.invokeAll(tasks);
        executor.shutdownNow();

        // if any of the updates failed then re-throw the first exception
        // (which will then be returned to WebSMS)
        for (int idx = 0; idx < results.size(); idx++) {
            Future<Void> result = results.get(idx);
            try {
                result.get();
            } catch (ExecutionException ex) {
                String subName = subs[idx].getName();
                throw new WebSMSException(
                        subName + ": " + ConnectorSpec.convertErrorMessage(context, ex.getCause()));
            }
        }
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
}

From source file:io.anserini.IndexerCW09B.java

public int indexWithThreads(int numThreads) throws IOException, InterruptedException {

    System.out.println(//from  w  w w  .j  a v a2 s.  co  m
            "Indexing with " + numThreads + " threads to directory '" + indexPath.toAbsolutePath() + "'...");

    final Directory dir = FSDirectory.open(indexPath);

    final IndexWriterConfig iwc = new IndexWriterConfig(analyzer());

    iwc.setSimilarity(new BM25Similarity());
    iwc.setIndexDeletionPolicy(NoDeletionPolicy.INSTANCE);
    iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    iwc.setRAMBufferSizeMB(256.0);
    iwc.setUseCompoundFile(false);
    iwc.setMergeScheduler(new ConcurrentMergeScheduler());

    final IndexWriter writer = new IndexWriter(dir, iwc);

    final ExecutorService executor = Executors.newFixedThreadPool(numThreads);

    for (Path f : discoverWarcFiles(docDir))
        executor.execute(new IndexerThread(writer, f));

    //add some delay to let some threads spawn by scheduler
    Thread.sleep(30000);
    executor.shutdown(); // Disable new tasks from being submitted

    try {
        // Wait for existing tasks to terminate
        while (!executor.awaitTermination(5, TimeUnit.MINUTES)) {
            Thread.sleep(1000);
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        executor.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }

    int numIndexed = writer.maxDoc();

    try {
        writer.commit();
    } finally {
        writer.close();
    }

    return numIndexed;
}

From source file:com.npstrandberg.simplemq.MessageQueueImp.java

private void shutdownAndAwaitTermination(ExecutorService pool) {

    pool.shutdown(); // Disable new tasks from being submitted

    try {/*from  w  w w .  j a v a2s .co  m*/

        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks

            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
                System.err.println("Pool did not terminate");
            }
        }
    } catch (InterruptedException ie) {

        // (Re-)Cancel if current thread also interrupted
        pool.shutdownNow();

        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }
}

From source file:com.esri.cordova.geolocation.AdvancedGeolocation.java

/**
 * Shutdown cordova thread pool. This assumes we are in control of all tasks running
 * in the thread pool.//ww w.ja  va 2  s .  c  o  m
 * Additional info: http://developer.android.com/reference/java/util/concurrent/ExecutorService.html
 * @param pool Cordova application's thread pool
 */
private void shutdownAndAwaitTermination(ExecutorService pool) {
    Log.d(TAG, "Attempting to shutdown cordova threadpool");
    if (!pool.isShutdown()) {
        try {
            // Disable new tasks from being submitted
            pool.shutdown();
            // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
                    System.err.println("Cordova thread pool did not terminate.");
                }
            }
        } catch (InterruptedException ie) {
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }
}