Example usage for com.google.common.util.concurrent ListeningExecutorService shutdown

List of usage examples for com.google.common.util.concurrent ListeningExecutorService shutdown

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ListeningExecutorService 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:com.github.rinde.rinsim.experiment.LocalComputer.java

static void checkForError(ListeningExecutorService executor, ResultCollector collector) {
    if (collector.hasError()) {
        LOGGER.info("Found error, shutting down. {}", collector.getFirstError());
        executor.shutdown();
        if (collector.getFirstError() instanceof RuntimeException) {
            throw (RuntimeException) collector.getFirstError();
        }//from ww  w  .ja v a2 s.  c  o  m
        throw new IllegalStateException(collector.getFirstError());
    }
}

From source file:com.b2international.snowowl.core.events.util.Promise.java

/**
 * @param func - the function to wrap into a {@link Promise}
 * @return//from ww w.  j av a2s.  c  om
 * @since 4.6
 */
@Beta
public static <T> Promise<T> wrap(final Callable<T> func) {
    final ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1));
    final ListenableFuture<T> submit = executor.submit(func);
    executor.shutdown();
    return wrap(submit);
}

From source file:org.apache.beam.runners.dataflow.util.PackageUtil.java

/**
 * Transfers the classpath elements to the staging location.
 *
 * @param classpathElements The elements to stage.
 * @param stagingPath The base location to stage the elements to.
 * @return A list of cloud workflow packages, each representing a classpath element.
 *//*w w w. ja v  a 2 s  .  com*/
static List<DataflowPackage> stageClasspathElements(Collection<String> classpathElements, String stagingPath,
        CreateOptions createOptions) {
    ListeningExecutorService executorService = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(32));
    try {
        return stageClasspathElements(classpathElements, stagingPath, Sleeper.DEFAULT, executorService,
                createOptions);
    } finally {
        executorService.shutdown();
    }
}

From source file:com.spotify.sparkey.system.ReloadableReaderExample.java

private static void run() throws IOException, InterruptedException, ExecutionException {
    ListeningExecutorService executorService = MoreExecutors
            .listeningDecorator(Executors.newSingleThreadExecutor());

    // create dummy log/index files, and load the reader from them
    final File logFile = new File("reloadabletest.spl");
    create(Sparkey.getIndexFile(logFile));
    final ReloadableSparkeyReader reader = ReloadableSparkeyReader.fromLogFile(logFile, executorService).get();

    // should be ignored (same file)
    reader.load(logFile);/* w  w  w.  ja v a2s.co m*/

    // should load from second file now
    final File logFile2 = new File("reloadabletest2.spl");
    create(Sparkey.getIndexFile(logFile2));
    reader.load(logFile2);

    reader.close();
    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    System.out.println("Done!");
}

From source file:com.google.cloud.dataflow.sdk.io.FileBasedSource.java

private static long getExactTotalSizeOfFiles(Collection<String> files, IOChannelFactory ioChannelFactory)
        throws Exception {
    List<ListenableFuture<Long>> futures = new ArrayList<>();
    ListeningExecutorService service = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(THREAD_POOL_SIZE));
    long totalSize = 0;
    try {/*from  w  ww .  j ava  2  s. c o m*/
        for (String file : files) {
            futures.add(createFutureForSizeEstimation(file, ioChannelFactory, service));
        }

        for (Long val : Futures.allAsList(futures).get()) {
            totalSize += val;
        }

        return totalSize;
    } finally {
        service.shutdown();
    }
}

From source file:com.github.tempora.concurrent.BackgroundTaskExecutor.java

private static <T> void execute(final BackgroundTask<T> task, boolean wait) {
    final ListeningExecutorService service = MoreExecutors.listeningDecorator(
            wait ? MoreExecutors.sameThreadExecutor() : Executors.newSingleThreadExecutor());
    try {//from www  .  j  a  v a2 s  . c o  m
        if (task instanceof LifecycleAware) {
            ((LifecycleAware) task).beforeCall();
        }
        final ListenableFuture<T> resultFuture = service.submit(task);
        task.relatedFuture = resultFuture;
        Futures.addCallback(resultFuture, task);
        if (task instanceof LifecycleAware) {
            Futures.addCallback(resultFuture, new FutureCallback<T>() {
                @Override
                public void onSuccess(T result) {
                    ((LifecycleAware) task).afterCall();
                }

                @Override
                public void onFailure(Throwable t) {
                    ((LifecycleAware) task).afterCall();
                }
            });
        }
        if (wait) {
            Futures.getUnchecked(resultFuture);
        }
    } finally {
        service.shutdown();
    }
}

From source file:org.attribyte.relay.AsyncPublisher.java

/**
 * Shutdown the publisher./*from  ww w  .  j  a  v  a 2s .  c o m*/
 * @param notificationExecutor The notification executor.
 * @param httpClient The HTTP client.
 * @param maxWaitSeconds The maximum amount of time to be patient for normal shutdown.
 * @throws Exception on shutdown error.
 */
private void shutdown(final ListeningExecutorService notificationExecutor, final HttpClient httpClient,
        final int maxWaitSeconds) throws Exception {
    if (isInit.compareAndSet(true, false)) {
        notificationExecutor.shutdown();
        notificationExecutor.awaitTermination(maxWaitSeconds, TimeUnit.SECONDS);
        if (!notificationExecutor.isShutdown()) {
            notificationExecutor.shutdownNow();
        }
        httpClient.stop();
    }
}

From source file:com.sk89q.worldguard.protection.managers.index.ChunkHashTable.java

/**
 * Waits until all currently executing background tasks complete.
 *
 * @param timeout the maximum time to wait
 * @param unit the time unit of the timeout argument
 * @return {@code true} if this executor terminated and
 *         {@code false} if the timeout elapsed before termination
 * @throws InterruptedException on interruption
 *//*from ww  w . j a v  a 2  s .  c  om*/
public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException {
    ListeningExecutorService previousExecutor;
    synchronized (lock) {
        previousExecutor = executor;
        executor = createExecutor();
    }
    previousExecutor.shutdown();
    return previousExecutor.awaitTermination(timeout, unit);
}

From source file:com.google.cloud.dataflow.sdk.util.GcsUtil.java

private static void executeBatches(List<BatchRequest> batches) throws IOException {
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(
            MoreExecutors.getExitingExecutorService(new ThreadPoolExecutor(MAX_CONCURRENT_BATCHES,
                    MAX_CONCURRENT_BATCHES, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())));

    List<ListenableFuture<Void>> futures = new LinkedList<>();
    for (final BatchRequest batch : batches) {
        futures.add(executor.submit(new Callable<Void>() {
            public Void call() throws IOException {
                batch.execute();/*from  w w  w .j  a v  a  2  s. com*/
                return null;
            }
        }));
    }

    try {
        Futures.allAsList(futures).get();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException("Interrupted while executing batch GCS request", e);
    } catch (ExecutionException e) {
        throw new IOException("Error executing batch GCS request", e);
    } finally {
        executor.shutdown();
    }
}

From source file:com.facebook.buck.cli.DistBuildCommandDelegate.java

private void killExecutor(ListeningExecutorService stampedeControllerExecutor, String failureWarning)
        throws InterruptedException {
    stampedeControllerExecutor.shutdown();
    if (!stampedeControllerExecutor.awaitTermination(STAMPEDE_EXECUTOR_SHUTDOWN_TIMEOUT_MILLIS,
            TimeUnit.MILLISECONDS)) {
        LOG.warn(failureWarning);//from  ww  w  .  j  a  v  a  2s .c  o  m
        stampedeControllerExecutor.shutdownNow();
    }
}