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.aipo.container.gadgets.AipoGadgetsGuiceModule.java

/** {@inheritDoc} */
@Override//from  w w w. ja  v  a  2s .c om
protected void configure() {

    bind(LockedDomainService.class).to(AipoHashLockedDomainService.class).in(Scopes.SINGLETON);
    bind(JsonRpcHandler.class).to(AipoJsonRpcHandler.class);
    bind(RpcServiceLookup.class).to(AipoRpcServiceLookup.class);

    final ExecutorService service = Executors.newCachedThreadPool(DAEMON_THREAD_FACTORY);
    bind(ExecutorService.class).toInstance(service);
    bind(ExecutorService.class).annotatedWith(Names.named("shindig.concat.executor")).toInstance(service);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            service.shutdownNow();
        }
    });

    install(new AipoParseModule());
    install(new PreloadModule());
    install(new RenderModule());
    install(new AipoRewriteModule());
    install(new SubstituterModule());
    install(new TemplateModule());
    install(new AipoUriModule());

    // bind(Long.class).annotatedWith(Names.named("org.apache.shindig.serviceExpirationDurationMinutes")).toInstance(60l);

    // We perform static injection on HttpResponse for cache TTLs.
    requestStaticInjection(HttpResponse.class);

    registerGadgetHandlers();
    registerConfigContributors();
    registerFeatureHandlers();
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Map<UpnpIgdDevice, byte[]> getRootXmlForEachDevice(Set<UpnpIgdDevice> devices)
        throws InterruptedException {
    Map<UpnpIgdDevice, byte[]> serviceRoots = new HashMap();

    ExecutorService executorService = null;
    try {//  ww w .j av  a  2s .co  m
        int maximumPoolSize = (int) ((double) Runtime.getRuntime().availableProcessors() / (1.0 - 0.95));
        executorService = new ThreadPoolExecutor(0, maximumPoolSize, 1, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());

        List<HttpRequestCallable<UpnpIgdDevice>> tasks = new LinkedList<>();
        for (UpnpIgdDevice device : devices) {
            tasks.add(new HttpRequestCallable<>(device.getUrl(), device));
        }

        List<Future<Pair<UpnpIgdDevice, byte[]>>> results = executorService.invokeAll(tasks);

        for (Future<Pair<UpnpIgdDevice, byte[]>> result : results) {
            try {
                Pair<UpnpIgdDevice, byte[]> data = result.get();
                serviceRoots.put(data.getKey(), data.getValue());
            } catch (InterruptedException | ExecutionException | CancellationException e) { // NOPMD
                // do nothing, skip
            }
        }
    } finally {
        if (executorService != null) {
            executorService.shutdownNow();
        }
    }

    return serviceRoots;
}

From source file:com.brienwheeler.lib.concurrent.ExecutorsTest.java

@Test
public void testNewSingleThreadExecutorShutdownNow() throws InterruptedException {
    NamedThreadFactory threadFactory = new NamedThreadFactory(THREAD_FACTORY_NAME);
    ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);

    executor.submit(new SleepRunnable(10L));
    Future<?> notExecutedRunnable = executor.submit(new NullRunnable());
    Future<?> notExecutedCallable = executor.submit(new NullCallable());
    Future<Integer> notEexecutedRunnable2 = executor.submit(new NullRunnable(), 1);

    List<Runnable> notExecuted = executor.shutdownNow();
    Assert.assertTrue(executor.isShutdown());
    Assert.assertEquals(3, notExecuted.size());
    Assert.assertTrue(CollectionUtils.containsInstance(notExecuted, notExecutedRunnable));
    Assert.assertTrue(CollectionUtils.containsInstance(notExecuted, notExecutedCallable));
    Assert.assertTrue(CollectionUtils.containsInstance(notExecuted, notEexecutedRunnable2));

    executor.awaitTermination(10, TimeUnit.MILLISECONDS);
    Assert.assertTrue(executor.isTerminated());
}

From source file:com.janrain.backplane2.server.config.Backplane2Config.java

@PreDestroy
private void cleanup() {
    Metrics.shutdown();/*w  ww  . j a v  a2s. c o  m*/

    for (ExecutorService executor : backgroundServices) {
        try {
            executor.shutdown();
            if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
                logger.info("Background thread shutdown properly");
            } else {
                executor.shutdownNow();
                if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                    logger.error("Background thread did not terminate");
                }
            }
        } catch (InterruptedException e) {
            logger.error("error shutting down background service", e);
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.polyvi.xface.extension.XExtensionManager.java

/**
 * //w w w .  j  a  va 2  s .  com
 */
private void shutdownAndAwaitTermination(ExecutorService pool) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(THREAD_POOL_TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(THREAD_POOL_TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS)) {
                XLog.d(CLASS_NAME, "Thread 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.ras.updater.Downloader.java

/**
 * This method will check for updates on all {@link #m_fileProviders} and download anything with an update.
 * @return true if at least one file was updated or false if no files were updated
 *//*  w ww  . j av a2s  . co m*/
public boolean update() {
    ArrayList<Future<Boolean>> results = new ArrayList<Future<Boolean>>();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (IFileProvider fileProvider : m_fileProviders) {
        FileUpdaterCallable task = new FileUpdaterCallable(fileProvider);
        results.add(es.submit(task));
    }
    es.shutdown();
    try {
        if (!es.awaitTermination(m_downloadTimeout, m_downloadTimeUnit))
            es.shutdownNow();
    } catch (InterruptedException e) {
        m_statusCallback.handleError(e);
        es.shutdownNow();
        Thread.currentThread().interrupt();
    }

    //Loop through the results for update values
    for (Future<Boolean> result : results) {
        try {
            if (result.isDone() && result.get() != null && result.get())
                return true;
        } catch (InterruptedException e) {
            //This should never happen
            m_statusCallback.handleError(e);
        } catch (ExecutionException e) {
            m_statusCallback.handleError(e);
        }
    }

    return false;
}

From source file:edu.cmu.cs.lti.ark.fn.identification.training.AlphabetCreationThreaded.java

/**
 * Splits frameElementLines into numThreads equally-sized batches and creates an alphabet
 * file for each one.//from   w ww.  ja v a2  s.com
 *
 * @throws IOException
 */
public Multiset<String> createAlphabet() throws IOException, ExecutionException, InterruptedException {
    final List<String> frameLines = Files.readLines(new File(frameElementsFile), Charsets.UTF_8)
            .subList(startIndex, endIndex);
    final int batchSize = (int) Math.ceil(frameLines.size() / (double) numThreads);
    final List<List<String>> frameLinesPartition = Lists.partition(frameLines, batchSize);
    final List<String> parseLines = Files.readLines(new File(parseFile), Charsets.UTF_8);
    final Multiset<String> alphabet = ConcurrentHashMultiset.create();
    final List<Callable<Integer>> jobs = Lists.newArrayListWithExpectedSize(numThreads);
    for (final int i : xrange(numThreads)) {
        jobs.add(newJob(i, frameLinesPartition.get(i), parseLines, alphabet));
    }
    final ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    final List<Future<Integer>> results = threadPool.invokeAll(jobs);
    threadPool.shutdown();
    try {
        for (Integer i : xrange(results.size())) {
            logger.info(String.format("Thread %d successfully processed %d lines", i, results.get(i).get()));
        }
    } finally {
        threadPool.shutdownNow();
    }
    return alphabet;
}

From source file:com.olacabs.fabric.compute.pipelined.ComuptationPipelineTest.java

@Test
public void testCheck() throws Exception {
    Properties properties = new Properties();
    properties.put("processor.counter_1.triggering_frequency", "1000");
    properties.put("processor.summer_1.triggering_frequency", "1000");
    properties.put("computation.shutdown.wait_time_in_seconds", "1");
    properties.put("computation.channel.channel_type", " disruptor");
    properties.put("computation.disruptor.buffer_size", "64");
    properties.put("computation.disruptor.wait_strategy", "Yield ");

    final String sourceId = "source_1";
    final String pid1 = "summer_1";
    final String pid2 = "counter_1";
    final String pid3 = "printer_1";

    RegisteringLoader loader = RegisteringLoader.builder()
            .source("memory", new MemoryBasedPipelineStreamPipelineSource())
            .stage("printer", new PrinterStreamingProcessor()).stage("summer", new SummingProcessor())
            .stage("counter", new CountingProcessor()).build();

    ComputationSpec spec = ComputationSpec.builder().name("test-pipeline")
            .source(ComponentInstance.builder().id(sourceId)
                    .meta(ComponentMetadata.builder().type(ComponentType.SOURCE).id(sourceId).name("memory")
                            .build())//www . j  av  a2s.c o  m
                    .build())
            .processor(ComponentInstance.builder().id(pid1)
                    .meta(ComponentMetadata.builder().type(ComponentType.PROCESSOR).id(pid1).name("summer")
                            .build())
                    .build())
            .processor(ComponentInstance.builder().id(pid2)
                    .meta(ComponentMetadata.builder().type(ComponentType.PROCESSOR).id(pid2).name("counter")
                            .build())
                    .build())
            .processor(ComponentInstance.builder().id(pid3)
                    .meta(ComponentMetadata.builder().type(ComponentType.PROCESSOR).id(pid3).name("printer")
                            .build())
                    .build())
            .connection(Connection.builder().fromType(ComponentType.SOURCE).from(sourceId).to(pid1).build())
            .connection(Connection.builder().fromType(ComponentType.SOURCE).from(sourceId).to(pid2).build())
            .connection(Connection.builder().fromType(ComponentType.SOURCE).from(sourceId).to(pid3).build())
            .connection(Connection.builder().fromType(ComponentType.PROCESSOR).from(pid1).to(pid3).build())
            .connection(Connection.builder().fromType(ComponentType.PROCESSOR).from(pid2).to(pid3).build())
            .properties(properties).build();
    System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(spec));

    Linker linker = new Linker(loader);
    ComputationPipeline pipeline = linker.build(spec);
    pipeline.initialize(properties);

    ExecutorService executor = Executors.newSingleThreadExecutor();

    ConsoleReporter reporter = ConsoleReporter
            .forRegistry(SharedMetricRegistries.getOrCreate("metrics-registry"))
            .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build();
    reporter.start(1, TimeUnit.SECONDS);
    executor.submit(pipeline::start);
    Thread.sleep(2000);
    pipeline.stop();
    reporter.stop();

    executor.shutdownNow();

}

From source file:org.bonej.wrapperPlugins.AnisotropyWrapper.java

private void shutdownAndAwaitTermination(final ExecutorService executor) {
    executor.shutdown(); // Disable new tasks from being submitted
    try {//from ww w .java2s.co  m
        // Wait a while for existing tasks to terminate
        if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
            executor.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                logService.trace("Pool did not terminate");
            }
        }
    } catch (final InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        executor.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
        logService.trace(ie);
    }
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Map<UpnpIgdServiceReference, byte[]> getServiceDescriptions(
        Set<UpnpIgdServiceReference> services) throws InterruptedException {
    Map<UpnpIgdServiceReference, byte[]> serviceXmls = new HashMap();

    ExecutorService executorService = null;
    try {/*from   w w  w  .  j  a  v  a 2  s .  c o m*/
        int maximumPoolSize = (int) ((double) Runtime.getRuntime().availableProcessors() / (1.0 - 0.95));
        executorService = new ThreadPoolExecutor(0, maximumPoolSize, 1, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());

        List<HttpRequestCallable<UpnpIgdServiceReference>> tasks = new LinkedList<>();
        for (UpnpIgdServiceReference service : services) {
            tasks.add(new HttpRequestCallable<>(service.getScpdUrl(), service));
        }

        List<Future<Pair<UpnpIgdServiceReference, byte[]>>> results = executorService.invokeAll(tasks);

        for (Future<Pair<UpnpIgdServiceReference, byte[]>> result : results) {
            try {
                Pair<UpnpIgdServiceReference, byte[]> data = result.get();
                serviceXmls.put(data.getKey(), data.getValue());
            } catch (InterruptedException | ExecutionException | CancellationException e) { // NOPMD
                // do nothing, skip
            }
        }
    } finally {
        if (executorService != null) {
            executorService.shutdownNow();
        }
    }

    return serviceXmls;
}