Example usage for java.util.concurrent ExecutorService shutdown

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

Introduction

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

Prototype

void shutdown();

Source Link

Document

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

Usage

From source file:Main.java

/**
 * <p>inokeInOtherThread</p>
 *
 * @param callable a Callable object.//from w w  w.  j  a  v  a 2 s .c o m
 * @return a T object.
 *
 * @throws ExecutionException   if any.
 * @throws InterruptedException if any.
 */
@Nullable
public static <T> T inokeInOtherThread(@Nonnull Callable<T> callable)
        throws ExecutionException, InterruptedException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        Future<T> future = executor.submit(callable);
        return future.get();
    } finally {
        executor.shutdown();
    }
}

From source file:com.buaa.cfs.utils.ShutdownThreadsHelper.java

/**
 * @param service {@link ExecutorService to be shutdown}
 * @param timeoutInMs time to wait for {@link
 * ExecutorService#awaitTermination(long, TimeUnit)}
 *                    calls in milli seconds.
 * @return <tt>true</tt> if the service is terminated,
 * <tt>false</tt> otherwise//  ww w  .jav  a 2s  .  c  o  m
 * @throws InterruptedException
 */
public static boolean shutdownExecutorService(ExecutorService service, long timeoutInMs)
        throws InterruptedException {
    if (service == null) {
        return true;
    }

    service.shutdown();
    if (!service.awaitTermination(timeoutInMs, TimeUnit.MILLISECONDS)) {
        service.shutdownNow();
        return service.awaitTermination(timeoutInMs, TimeUnit.MILLISECONDS);
    } else {
        return true;
    }
}

From source file:Main.java

public static void runRunnablesNTimesAndAwaitCompletion(int times, final List<Runnable> runnables)
        throws InterruptedException {
    ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(runnables.size());
    for (Runnable r : runnables) {
        for (int i = 0; i < times; i++) {
            newFixedThreadPool.execute(r);
        }/*w  ww  .ja  v a 2  s  .  c o  m*/
    }
    newFixedThreadPool.shutdown();
    newFixedThreadPool.awaitTermination(5, TimeUnit.SECONDS);
}

From source file:baggage.BaseTestCase.java

protected static void attempt(Runnable task) {
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    executorService.submit(task);//from   w w  w .j a  v  a 2s  .c o m
    executorService.shutdown();
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static boolean stop(ExecutorService executorService, int waitBeforeTerminateSecs, Logger logger)
/*     */ {/*from   w w w .  j a v  a2 s .c  o m*/
    /*  53 */int waitMillis = Math.max(1000, 1000 * waitBeforeTerminateSecs);
    /*     */
    /*     */
    /*  56 */executorService.shutdown();
    /*     */
    /*     */
    /*  59 */boolean stopped = false;
    /*  60 */while ((waitMillis > 0) && (!stopped)) {
        /*  61 */long startMillis = System.currentTimeMillis();
        /*     */try {
            /*  63 */logger.debug("Waiting for thread pool to stop");
            /*  64 */stopped = executorService.awaitTermination(waitMillis, TimeUnit.MILLISECONDS);
            /*     */} catch (InterruptedException e) {
            /*  66 */logger.debug("Thread was interrupted while it was waiting for thread pool to stop", e);
            /*  67 */Thread.currentThread().interrupt();
            /*  68 */break;
            /*     */}
        /*  70 */waitMillis = (int) (waitMillis - (System.currentTimeMillis() - startMillis));
        /*     */}
    /*     */
    /*  73 */if (!executorService.isTerminated()) {
        /*  74 */logger.warn("Thread pool will be forcibly stopped now if it has not already stopped");
        /*  75 */executorService.shutdownNow();
        /*     */try {
            /*  77 */stopped = executorService.awaitTermination(waitBeforeTerminateSecs, TimeUnit.SECONDS);
            /*     */}
        /*     */catch (InterruptedException e) {
        }
        /*     */
        /*  81 */if (!executorService.isTerminated()) {
            /*  82 */logger.warn("Could not shutdown thread pool in [{}] seconds",
                    Integer.valueOf(waitBeforeTerminateSecs));
            /*     */}
        /*     */}
    /*     */
    /*  86 */return stopped;
    /*     */}

From source file:Main.java

public static <T> List<T> executeParallel(final List<Callable<T>> callables, final int maxThreadCount)
        throws InterruptedException, ExecutionException {
    final int threadCount = callables.size() > 0 && callables.size() < maxThreadCount ? callables.size()
            : maxThreadCount;// w  ww. j  av a 2s  .  co  m
    ExecutorService executor = newFixedThreadPool(threadCount);
    List<T> results = new ArrayList<>();
    try {
        for (Future<T> future : executor.invokeAll(callables)) {
            results.add(future.get());
        }
    } finally {
        executor.shutdown();
    }
    return results;
}

From source file:Main.java

/**
 * Runs and blocking waits for the given callable to finish for the given
 * time. Returns <code>null</code> if timeouts waiting for callable value.
 * //w  ww  .ja  v  a 2s .c  o m
 * @param millisTimeout
 * @param callable
 * @return
 */
public static <R> R runWithTimeout(long millisTimeout, Callable<R> callable) {
    ExecutorService singleThreadExecutor = Executors.newFixedThreadPool(1);
    Future<R> future = singleThreadExecutor.submit(callable);
    try {
        return future.get(millisTimeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
    } finally {
        singleThreadExecutor.shutdown();
    }
    return null;
}

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 {/*from   w  ww  .j  a va2s  .  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:com.netsteadfast.greenstep.util.SystemExpressionJobUtils.java

public static SysExprJobLogVO executeJobForManual(String expressionJobOid) throws ServiceException, Exception {
    ExpressionJobObj jobObj = getExpressionJobForManualMode(expressionJobOid);
    ExecutorService exprJobPool = Executors.newFixedThreadPool(1);
    jobObj = exprJobPool.submit(new ExpressionJobExecuteCallable(jobObj)).get();
    exprJobPool.shutdown();
    return jobObj.getSysExprJobLog();
}

From source file:com.uniteddev.Unity.Downloader.java

public static void renameFiles() throws IOException, InterruptedException {
    Login.progressText.setText("Renaming files...");
    System.out.println("Renaming files...");
    class renameFile implements Runnable {
        private int i;

        renameFile(int i) {
            this.i = i;
        }/*from  w  w  w.j  av  a2s.com*/

        public void run() {
            //System.out.println("Currently attempting Pool Index: "+this.i);
            String file = rename_files.get(this.i);
            if (file.contains("%20") || file.contains("%5b") || file.contains("%5d")) {
                file = namefix(file);
                File oldfile = new File(Minecraft.getWorkingDirectory(), rename_files.get(this.i));
                if (oldfile.exists()) {
                    File newfile = new File(Minecraft.getWorkingDirectory(), file);
                    oldfile.renameTo(newfile);
                    System.out.println("Renamed " + oldfile.getName() + " to " + newfile.getName());
                }
            }

        }
    }
    ExecutorService pool = Executors.newFixedThreadPool(cores + 4);
    for (int i = 0; i < rename_files.size(); i++) {
        pool.submit(new renameFile(i));
    }
    pool.shutdown();
    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}