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.janrain.backplane.config.BackplaneConfig.java

private void shutdownExecutor(String serviceName, ExecutorService executor) {
    try {/*from  w ww .  j  a va  2s.  c o  m*/
        executor.shutdown();
        if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
            logger.info(serviceName + " background thread shutdown properly");
        } else {
            executor.shutdownNow();
            if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                logger.error(serviceName + " background thread did not terminate");
            }
        }
    } catch (InterruptedException e) {
        logger.error(serviceName + " termination threw an exception", e);
        executor.shutdownNow();
        Thread.currentThread().interrupt();
    }
}

From source file:com.nts.alphamale.handler.ExecutorHandler.java

public void shutdownExecutor(ExecutorService executor, int awaitTermination) {
    if (null != executor && !executor.isShutdown()) {
        executor.shutdown();/*  www.  j a v  a 2 s. co  m*/
        try {
            if (!executor.awaitTermination(awaitTermination, TimeUnit.SECONDS)) {
                executor.shutdownNow();
                if (!executor.awaitTermination(awaitTermination, TimeUnit.SECONDS)) {
                    log.error("Executor did not terminate");
                }
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
}

From source file:io.cloudslang.content.utilities.util.ProcessExecutor.java

public ProcessResponseEntity execute(String commandLine, int timeout)
        throws IOException, ExecutionException, InterruptedException, TimeoutException {
    Process process = new ProcessBuilder().command(processCommand(commandLine)).start();

    ProcessStreamConsumer processStreamConsumer = new ProcessStreamConsumer(process);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    Future<ProcessResponseEntity> futureResult = executor.submit(processStreamConsumer);

    try {//from  w ww . j  av  a  2  s  .  c o m
        return futureResult.get(timeout, MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        stopProcess(process, futureResult);
        throw e;
    } finally {
        executor.shutdownNow();
    }
}

From source file:com.janrain.backplane.server.config.Backplane1Config.java

@PreDestroy
private void cleanup() {
    for (ExecutorService executor : backgroundServices) {
        try {//from w w w  . j  av  a2s . co  m
            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.sangupta.httptools.DownloadUrlCommand.java

/**
 * Terminate the thread pool/*from  w  ww  . j  ava 2 s  .co m*/
 * 
 * @param pool
 *            the thread pool to terminate
 */
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(1, TimeUnit.DAYS)) {
            pool.shutdownNow(); // Cancel currently executing tasks

            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(60, 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:org.apache.shindig.gadgets.DefaultGuiceModule.java

/** {@inheritDoc} */
@Override// w  w w.j a  va2 s.  c o  m
protected void configure() {

    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() {
        public void run() {
            service.shutdownNow();
        }
    });

    install(new ParseModule());
    install(new PreloadModule());
    install(new RenderModule());
    install(new RewriteModule());
    install(new SubstituterModule());
    install(new TemplateModule());
    install(new UriModule());

    // 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:org.neo4j.ogm.integration.TransactionRequestHandlerTest.java

@Test
public void shouldBeAbleToStartMultipleConcurrentLongRunningTransactions() throws InterruptedException {

    SessionFactory sessionFactory = new SessionFactory();
    session = sessionFactory.openSession(neo4jRule.url());

    int numThreads = 100;

    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
    CountDownLatch latch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        executor.submit(new TransactionStarter(latch));
    }/*  w  w  w  .j  av a  2 s  . c  o  m*/
    latch.await(); // pause until the count reaches 0
    System.out.println("all threads running");
    executor.shutdownNow();
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

/**
 * Initializes war configuration directory for a Cadmium war.
 * @param uri The remote Git repository ssh URI.
 * @param branch The remote branch to checkout.
 * @param root The shared root.//from  w w  w . j  ava 2 s.c  om
 * @param warName The name of the war file.
 * @param historyManager The history manager to log the initialization event.
 * @return A GitService object the points to the freshly cloned Git repository.
 * @throws RefNotFoundException
 * @throws Exception
 */
public static GitService initializeConfigDirectory(String uri, String branch, String root, String warName,
        HistoryManager historyManager, ConfigManager configManager) throws Exception {
    initializeBaseDirectoryStructure(root, warName);
    String warDir = FileSystemManager.getChildDirectoryIfExists(root, warName);

    Properties configProperties = configManager.getDefaultProperties();

    GitLocation gitLocation = new GitLocation(uri, branch, configProperties.getProperty("config.git.ref.sha"));
    GitService cloned = initializeRepo(gitLocation, warDir, "git-config-checkout");

    try {
        String renderedContentDir = initializeSnapshotDirectory(warDir, configProperties,
                "com.meltmedia.cadmium.config.lastUpdated", "git-config-checkout", "config");

        boolean hasExisting = configProperties.containsKey("com.meltmedia.cadmium.config.lastUpdated")
                && renderedContentDir != null && renderedContentDir
                        .equals(configProperties.getProperty("com.meltmedia.cadmium.config.lastUpdated"));
        if (renderedContentDir != null) {
            configProperties.setProperty("com.meltmedia.cadmium.config.lastUpdated", renderedContentDir);
        }
        configProperties.setProperty("config.branch", cloned.getBranchName());
        configProperties.setProperty("config.git.ref.sha", cloned.getCurrentRevision());
        configProperties.setProperty("config.repo", cloned.getRemoteRepository());

        configManager.persistDefaultProperties();

        ExecutorService pool = null;
        if (historyManager == null) {
            pool = Executors.newSingleThreadExecutor();
            historyManager = new HistoryManager(warDir, pool);
        }

        try {
            if (historyManager != null && !hasExisting) {
                historyManager.logEvent(EntryType.CONFIG,
                        // NOTE: We should integrate the git pointer into this class.
                        new GitLocation(cloned.getRemoteRepository(), cloned.getBranchName(),
                                cloned.getCurrentRevision()),
                        "AUTO", renderedContentDir, "", "Initial config pull.", true, true);
            }
        } finally {
            if (pool != null) {
                pool.shutdownNow();
            }
        }
        return cloned;
    } catch (Throwable e) {
        cloned.close();
        throw new Exception(e);
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.dns.ZoneManager.java

protected static void initZoneCache(final TrafficRouter tr) {
    synchronized (ZoneManager.class) {
        final CacheRegister cacheRegister = tr.getCacheRegister();
        final JSONObject config = cacheRegister.getConfig();

        int poolSize = 1;
        final double scale = config.optDouble("zonemanager.threadpool.scale", 0.75);
        final int cores = Runtime.getRuntime().availableProcessors();

        if (cores > 2) {
            final Double s = Math.floor((double) cores * scale);

            if (s.intValue() > 1) {
                poolSize = s.intValue();
            }//from   ww w.j  a  v a  2s .c om
        }

        final ExecutorService initExecutor = Executors.newFixedThreadPool(poolSize);

        final ExecutorService ze = Executors.newFixedThreadPool(poolSize);
        final ScheduledExecutorService me = Executors.newScheduledThreadPool(2); // 2 threads, one for static, one for dynamic, threads to refresh zones
        final int maintenanceInterval = config.optInt("zonemanager.cache.maintenance.interval", 300); // default 5 minutes
        final String dspec = "expireAfterAccess="
                + config.optString("zonemanager.dynamic.response.expiration", "300s"); // default to 5 minutes

        final LoadingCache<ZoneKey, Zone> dzc = createZoneCache(ZoneCacheType.DYNAMIC,
                CacheBuilderSpec.parse(dspec));
        final LoadingCache<ZoneKey, Zone> zc = createZoneCache(ZoneCacheType.STATIC);

        initZoneDirectory();

        try {
            LOGGER.info("Generating zone data");
            generateZones(tr, zc, dzc, initExecutor);
            initExecutor.shutdown();
            initExecutor.awaitTermination(5, TimeUnit.MINUTES);
            LOGGER.info("Zone generation complete");
        } catch (final InterruptedException ex) {
            LOGGER.warn("Initialization of zone data exceeded time limit of 5 minutes; continuing", ex);
        } catch (IOException ex) {
            LOGGER.fatal("Caught fatal exception while generating zone data!", ex);
        }

        me.scheduleWithFixedDelay(getMaintenanceRunnable(dzc, ZoneCacheType.DYNAMIC, maintenanceInterval), 0,
                maintenanceInterval, TimeUnit.SECONDS);
        me.scheduleWithFixedDelay(getMaintenanceRunnable(zc, ZoneCacheType.STATIC, maintenanceInterval), 0,
                maintenanceInterval, TimeUnit.SECONDS);

        final ExecutorService tze = ZoneManager.zoneExecutor;
        final ScheduledExecutorService tme = ZoneManager.zoneMaintenanceExecutor;
        final LoadingCache<ZoneKey, Zone> tzc = ZoneManager.zoneCache;
        final LoadingCache<ZoneKey, Zone> tdzc = ZoneManager.dynamicZoneCache;

        ZoneManager.zoneExecutor = ze;
        ZoneManager.zoneMaintenanceExecutor = me;
        ZoneManager.dynamicZoneCache = dzc;
        ZoneManager.zoneCache = zc;

        if (tze != null) {
            tze.shutdownNow();
        }

        if (tme != null) {
            tme.shutdownNow();
        }

        if (tzc != null) {
            tzc.invalidateAll();
        }

        if (tdzc != null) {
            tdzc.invalidateAll();
        }
    }
}

From source file:org.apache.streams.facebook.provider.FacebookFriendFeedProvider.java

void shutdownAndAwaitTermination(ExecutorService pool) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {//from   w  w w.ja v  a 2 s  .co m
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(10, 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();
    }
}