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:Main.java

public static void stop(ExecutorService executor) {
    try {//  w  w w . j a v a 2  s  .  co m
        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        System.err.println("termination interrupted");
    } finally {
        if (!executor.isTerminated()) {
            System.err.println("killing non-finished tasks");
        }
        executor.shutdownNow();
    }
}

From source file:Main.java

public static void stop(ExecutorService executor) {
    try {/*w  w  w  .  j a va 2s.  c  om*/
        executor.shutdown();
        executor.awaitTermination(60, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        System.err.println("termination interrupted");
    } finally {
        if (!executor.isTerminated()) {
            System.err.println("killing non-finished tasks");
        }
        executor.shutdownNow();
    }
}

From source file:Main.java

public static void stop(ExecutorService executor) {
    try {/*from w w  w  . j  a v  a2 s .  c o m*/
        executor.shutdown();
        executor.awaitTermination(60, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        System.err.println("termination interrupted");
    } finally {
        if (!executor.isTerminated()) {
            System.out.println("killing non-finished tasks");
        }
        executor.shutdownNow();
    }
}

From source file:org.deeplearning4j.clustering.cluster.ClusterUtils.java

public static ClusterSetInfo computeClusterSetInfo(ClusterSet clusterSet) {
    ExecutorService executor = MultiThreadUtils.newExecutorService();
    ClusterSetInfo info = computeClusterSetInfo(clusterSet, executor);
    executor.shutdownNow();
    return info;/*from   w w w  .ja v  a2  s .c  om*/
}

From source file:gobblin.aws.GobblinAWSUtils.java

/***
 * Initiates an orderly shutdown in which previously submitted
 * tasks are executed, but no new tasks are accepted.
 * Invocation has no additional effect if already shut down.
 *
 * This also blocks until all tasks have completed execution
 * request, or the timeout occurs, or the current thread is
 * interrupted, whichever happens first.
 * @param clazz {@link Class} that invokes shutdown on the {@link ExecutorService}.
 * @param executorService {@link ExecutorService} to shutdown.
 * @param logger {@link Logger} to log shutdown for invoking class.
 * @throws InterruptedException if shutdown is interrupted.
 *///from w w  w  . j ava  2 s .  co m
public static void shutdownExecutorService(Class clazz, ExecutorService executorService, Logger logger)
        throws InterruptedException {
    executorService.shutdown();
    if (!executorService.awaitTermination(DEFAULT_EXECUTOR_SERVICE_SHUTDOWN_TIME_IN_MINUTES,
            TimeUnit.MINUTES)) {
        logger.warn("Executor service shutdown timed out.");
        List<Runnable> pendingTasks = executorService.shutdownNow();
        logger.warn(String.format("%s was shutdown instantly. %s tasks were not executed: %s", clazz.getName(),
                pendingTasks.size(), StringUtils.join(pendingTasks, ",")));
    }
}

From source file:org.apache.phoenix.util.PhoenixMRJobUtil.java

public static void shutdown(ExecutorService pool) throws InterruptedException {
    pool.shutdown();// ww  w  .ja v a  2s.co m
    LOG.debug("Shutdown called");
    pool.awaitTermination(200, TimeUnit.MILLISECONDS);
    LOG.debug("Await termination called to wait for 200 msec");
    if (!pool.isShutdown()) {
        pool.shutdownNow();
        LOG.debug("Await termination called to wait for 200 msec");
        pool.awaitTermination(100, TimeUnit.MILLISECONDS);
    }
    if (!pool.isShutdown()) {
        LOG.warn("Pool did not shutdown");
    }
}

From source file:com.aol.advertising.qiao.util.CommonUtils.java

public static void shutdownAndAwaitTermination(ExecutorService pool, int waitTime, TimeUnit timeUnit) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {// www  . j a  va2  s  .  c  o m
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(waitTime, timeUnit)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(waitTime, timeUnit))
                logger.warn("Executor did not terminate");
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        pool.shutdownNow();
    }
}

From source file:net.ymate.platform.module.search.Searchs.java

public static void __doStopSafed(ExecutorService pool) {
    if (pool != null) {
        pool.shutdown();/*from ww  w . j  ava 2 s.c  o  m*/
        try {
            if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
                pool.shutdownNow();
            }
        } catch (InterruptedException ex) {
            // Nothing..
            ex.printStackTrace();
        }
    }
}

From source file:kindleclippings.quizlet.GetAccessToken.java

static JSONObject oauthDance() throws IOException, URISyntaxException, InterruptedException, JSONException {

    // start HTTP server, so when can get the authorization code
    InetSocketAddress addr = new InetSocketAddress(7777);
    HttpServer server = HttpServer.create(addr, 0);
    AuthCodeHandler handler = new AuthCodeHandler();
    server.createContext("/", handler);
    ExecutorService ex = Executors.newCachedThreadPool();
    server.setExecutor(ex);/*  w  ww  .  j  a  v  a2  s  .  com*/
    server.start();
    String authCode;
    try {
        Desktop.getDesktop()
                .browse(new URI(new StringBuilder("https://quizlet.com/authorize/")
                        .append("?scope=read%20write_set").append("&client_id=" + clientId)
                        .append("&response_type=code").append("&state=" + handler.state).toString()));

        authCode = handler.result.take();
    } finally {
        server.stop(0);
        ex.shutdownNow();
    }

    if (authCode == null || authCode.length() == 0)
        return null;

    HttpPost post = new HttpPost("https://api.quizlet.com/oauth/token");
    post.setHeader("Authorization", authHeader);

    post.setEntity(
            new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("grant_type", "authorization_code"),
                    new BasicNameValuePair("code", authCode))));
    HttpResponse response = new DefaultHttpClient().execute(post);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(1000);
    response.getEntity().writeTo(buffer);
    return new JSONObject(new String(buffer.toByteArray(), "UTF-8"));
}

From source file:org.apache.stratos.common.threading.StratosThreadPool.java

public static void shutdown(String identifier) {

    ExecutorService executorService = executorServiceMap.get(identifier);
    if (executorService == null) {
        log.warn("No executor service found for id " + identifier + ", unable to shut down");
        return;/*w  w w .j a v  a 2  s  .c  o  m*/
    }

    // try to shut down gracefully
    executorService.shutdown();
    // wait 10 secs till terminated
    try {
        if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
            log.info("Thread Pool [id] " + identifier + " did not finish all tasks before "
                    + "timeout, forcefully shutting down");
            executorService.shutdownNow();
        }
    } catch (InterruptedException e) {
        // interrupted, shutdown now
        executorService.shutdownNow();
    }

    // remove from the map
    executorServiceMap.remove(identifier);

    log.info("Successfully shutdown thread pool associated with id: " + identifier);
}