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

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

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ListeningExecutorService 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.google.cloud.bigtable.grpc.async.ResourceLimiterPerf.java

public static void main(String[] args) throws Exception {
    ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    try {/*from   ww  w .  j  a va  2 s .  com*/
        for (int i = 0; i < 10; i++) {
            System.out.println("=======");
            test(pool);
        }
    } finally {
        pool.shutdownNow();
    }
}

From source file:se.softhouse.common.testlib.Concurrently.java

/**
 * Returns a {@link ListenableFuture} running {@code callable} asynchronously. When this method
 * returns the {@link Callable#call()} may have been run or it may not. Call
 * {@link Future#get()} on the returned {@link Future} to get the result from the calculation.
 * The {@link Executor} running the returned {@link Future} is automatically shutdown when it's
 * done. If threads should be reused and performance is critical you should roll your own and
 * reuse the executor instead.//from   w w w  . j av a  2  s.  co m
 */
public static <T> ListenableFuture<T> run(Callable<T> callable) {
    final ListeningExecutorService executor = listeningDecorator(newSingleThreadExecutor());
    ListenableFuture<T> futureForCallable = executor.submit(callable);
    Futures.addCallback(futureForCallable, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            executor.shutdownNow();
        }

        @Override
        public void onFailure(Throwable t) {
            executor.shutdownNow();
        }
    });
    return futureForCallable;
}

From source file:org.excalibur.core.util.concurrent.Futures2.java

public static <V> List<V> invokeAllAndShutdownWhenFinish(List<Callable<V>> tasks,
        ListeningExecutorService executor, FutureCallback<V>[] callbacks) {
    final List<V> results = Lists.newArrayList();
    final CountDownLatch endSignal = new CountDownLatch(tasks.size());

    FutureCallback<V> endSignalCallback = new FutureCallback<V>() {
        @Override//w ww .  jav a  2 s .  c om
        public void onSuccess(@Nullable V result) {
            endSignal.countDown();
            results.add(result);
        }

        @Override
        public void onFailure(Throwable t) {
            endSignal.countDown();
        }
    };

    List<FutureCallback<V>> l = Lists.newArrayList(callbacks);
    l.add(endSignalCallback);

    invokeAll(tasks, executor, l.toArray(new FutureCallback[l.size()]));

    try {
        endSignal.await();
        executor.shutdownNow();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return results;
}

From source file:com.google.pubsub.clients.common.LoadTestRunner.java

private static void runTest(StartRequest request) {
    log.info("Request received, starting up server.");
    ListeningExecutorService executor = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(request.getMaxOutstandingRequests() + 10));

    final RateLimiter rateLimiter = RateLimiter.create(request.getRequestRate());
    final Semaphore outstandingTestLimiter = new Semaphore(request.getMaxOutstandingRequests(), false);

    final long toSleep = request.getStartTime().getSeconds() * 1000 - System.currentTimeMillis();
    if (toSleep > 0) {
        try {/*from ww w.j  av a 2 s . com*/
            Thread.sleep(toSleep);
        } catch (InterruptedException e) {
            log.error("Interrupted sleeping, starting test now.");
        }
    }

    stopwatch.start();
    while (shouldContinue(request)) {
        outstandingTestLimiter.acquireUninterruptibly();
        rateLimiter.acquire();
        executor.submit(task).addListener(outstandingTestLimiter::release, executor);
    }
    stopwatch.stop();
    executor.shutdownNow();
    finished.set(true);
    log.info("Load test complete.");
}

From source file:org.apache.jclouds.profitbricks.rest.compute.concurrent.ProvisioningManager.java

@Override
public void close() throws IOException {
    terminated.set(true); // Do not allow to enqueue more jobs
    Collection<ListeningExecutorService> executors = workers.values();
    for (ListeningExecutorService executor : executors) {
        List<Runnable> runnables = executor.shutdownNow();
        if (!runnables.isEmpty()) {
            logger.warn("when shutting down executor %s, runnables outstanding: %s", executor, runnables);
        }/*from  w w  w  .j a v a 2s  . co  m*/
    }
}

From source file:org.jclouds.profitbricks.compute.concurrent.ProvisioningManager.java

@Override
public void close() throws IOException {
    terminated.set(true); // Do not allow to enqueue more jobs
    Collection<ListeningExecutorService> executors = workers.values();
    for (ListeningExecutorService executor : executors) {
        List<Runnable> runnables = executor.shutdownNow();
        if (!runnables.isEmpty())
            logger.warn("when shutting down executor %s, runnables outstanding: %s", executor, runnables);
    }//ww w  .ja va2 s .co m
}

From source file:org.apache.brooklyn.location.jclouds.JcloudsUtil.java

public static String getFirstReachableAddress(NodeMetadata node, Duration timeout) {
    final int port = node.getLoginPort();
    List<HostAndPort> sockets = FluentIterable
            .from(Iterables.concat(node.getPublicAddresses(), node.getPrivateAddresses()))
            .transform(new Function<String, HostAndPort>() {
                @Override/*from w w  w  .jav a 2 s. c  o  m*/
                public HostAndPort apply(String input) {
                    return HostAndPort.fromParts(input, port);
                }
            }).toList();

    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    try {
        ReachableSocketFinder finder = new ReachableSocketFinder(executor);
        HostAndPort result = finder.findOpenSocketOnNode(sockets, timeout);
        return result.getHostText();
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        throw new IllegalStateException("Unable to connect SshClient to " + node
                + "; check that the node is accessible and that the SSH key exists and is correctly configured, including any passphrase defined",
                e);
    } finally {
        executor.shutdownNow();
    }
}

From source file:org.robotninjas.barge.RaftModule.java

@Override
protected void configure() {

    install(new StateModule(timeout));
    Replica local = config.local();// w w  w. java2 s .  c  o  m

    final NioEventLoopGroup eventLoop;
    if (eventLoopGroup.isPresent()) {
        eventLoop = eventLoopGroup.get();
    } else {
        eventLoop = new NioEventLoopGroup();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                eventLoop.shutdownGracefully();
            }
        });
    }
    install(new RpcModule(local.address(), eventLoop));

    final ListeningExecutorService executor;
    if (stateMachineExecutor.isPresent()) {
        executor = stateMachineExecutor.get();
    } else {
        executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                executor.shutdownNow();
            }
        });
    }
    install(new LogModule(logDir, stateMachine, executor));

    bind(ClusterConfig.class).toInstance(config);

    bind(RaftService.class);
    expose(RaftService.class);

}

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

/**
 * Clear the current hash table and rebuild it in the background.
 *//*from w w  w .j  a  va  2  s.  c  om*/
private void rebuild() {
    synchronized (lock) {
        ListeningExecutorService previousExecutor = executor;
        LongHashTable<ChunkState> previousStates = states;

        previousExecutor.shutdownNow();
        states = new LongHashTable<>();
        executor = createExecutor();

        List<BlockVector2> positions = new ArrayList<>();
        for (ChunkState state : previousStates.values()) {
            BlockVector2 position = state.getPosition();
            positions.add(position);
            states.put(position.getBlockX(), position.getBlockZ(), new ChunkState(position));
        }

        if (!positions.isEmpty()) {
            executor.submit(new EnumerateRegions(positions));
        }

        lastState = null;
    }
}

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

/**
 * Shutdown the publisher./*from  ww  w  .  j  a  v  a  2 s .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();
    }
}