Example usage for com.google.common.util.concurrent MoreExecutors sameThreadExecutor

List of usage examples for com.google.common.util.concurrent MoreExecutors sameThreadExecutor

Introduction

In this page you can find the example usage for com.google.common.util.concurrent MoreExecutors sameThreadExecutor.

Prototype

@Deprecated
@GwtIncompatible("TODO")
public static ListeningExecutorService sameThreadExecutor() 

Source Link

Document

Creates an executor service that runs each task in the thread that invokes execute/submit , as in CallerRunsPolicy .

Usage

From source file:info.archinnov.achilles.internal.async.AsyncUtils.java

public void maybeAddAsyncListeners(ListenableFuture<?> listenableFuture, Options options) {
    maybeAddAsyncListeners(listenableFuture, options, MoreExecutors.sameThreadExecutor());
}

From source file:org.jboss.arquillian.jbehave.examples.container.ExchangeCurrenciesInContainer.java

public ExchangeCurrenciesInContainer() {
    /* /*from w w w. j a v a 2  s .c o m*/
     * Configure JBehave to use the Guava SameThreadExecutorService.
     * This enables the ArquillianInstanceStepsFactory to access
     * the ThreadLocal contexts and datastores.
     */
    configuredEmbedder().useExecutorService(MoreExecutors.sameThreadExecutor());
}

From source file:org.jboss.arquillian.jbehave.examples.client.ExchangeCurrencies.java

public ExchangeCurrencies() {
    /*/*from  w w  w. j  a  v a 2s  . c o  m*/
     * Configure JBehave to use the Guava SameThreadExecutorService.
     * This enables the ArquillianInstanceStepsFactory to access
     * the ThreadLocal contexts and datastores.
     */
    configuredEmbedder().useExecutorService(MoreExecutors.sameThreadExecutor());
}

From source file:zookeeper.recipes.leader.LeaderSelector.java

/**
 * @param client the client/*from   www. j a va  2  s . c  o m*/
 * @param leaderPath the path for this leadership group
 * @param listener listener
 */
public LeaderSelector(CuratorFramework client, String leaderPath, LeaderSelectorListener listener) {
    this(client, leaderPath, defaultThreadFactory, MoreExecutors.sameThreadExecutor(), listener);
}

From source file:org.jenkinsci.plugins.workflow.support.concurrent.Futures.java

/**
 * Registers separate success and failure callbacks to be run when the {@code
 * Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
 * complete} or, if the computation is already complete, immediately.
 *
 * <p>There is no guaranteed ordering of execution of callbacks, but any
 * callback added through this method is guaranteed to be called once the
 * computation is complete.//from ww  w . ja va  2s  .co m
 *
 * Example: <pre> {@code
 * ListenableFuture<QueryResult> future = ...;
 * addCallback(future,
 *     new FutureCallback<QueryResult> {
 *       public void onSuccess(QueryResult result) {
 *         storeInCache(result);
 *       }
 *       public void onFailure(Throwable t) {
 *         reportError(t);
 *       }
 *     });}</pre>
 *
 * <p>Note: This overload of {@code addCallback} is designed for cases in
 * which the callack is fast and lightweight, as the method does not accept
 * an {@code Executor} in which to perform the the work. For heavier
 * callbacks, this overload carries some caveats: First, the thread that the
 * callback runs in depends on whether the input {@code Future} is done at the
 * time {@code addCallback} is called and on whether the input {@code Future}
 * is ever cancelled. In particular, {@code addCallback} may execute the
 * callback in the thread that calls {@code addCallback} or {@code
 * Future.cancel}. Second, callbacks may run in an internal thread of the
 * system responsible for the input {@code Future}, such as an RPC network
 * thread. Finally, during the execution of a {@code sameThreadExecutor}
 * callback, all other registered but unexecuted listeners are prevented from
 * running, even if those listeners are to run in other executors.
 *
 * <p>For a more general interface to attach a completion listener to a
 * {@code Future}, see {@link ListenableFuture#addListener addListener}.
 *
 * @param future The future attach the callback to.
 * @param callback The callback to invoke when {@code future} is completed.
 * @since 10.0
 */
public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback) {
    addCallback(future, callback, MoreExecutors.sameThreadExecutor());
}

From source file:org.robotninjas.concurrent.FluentFutureTask.java

@Override
public FluentFuture<V> onSuccess(final Consumer<V> callback) {
    return onSuccess(MoreExecutors.sameThreadExecutor(), callback);
}

From source file:org.blackbananacoin.incubator.extbitcoinj.SendCoinBack.java

@Override
protected void postCheckKeyOk() {

    checkNotNull(getWallet());//  w w  w. java2s .c o  m

    Wallet w = getWallet();

    checkNotNull(getParam());

    try {
        Address tpfaucetAddress;
        tpfaucetAddress = new Address(getParam(), ADDR_tpfaucet_appspot_com);
        // send 500x min tx fee back.
        BigInteger value = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE
                .multiply(BigInteger.valueOf(AmountMultiplyTxFee));
        System.out.println("Sendback " + value + "=" + Utils.bitcoinValueToFriendlyString(value) + " BTC");
        // Now send the coins back! Send with a small fee attached to ensure
        // rapid confirmation.
        final BigInteger amountToSend = value.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
        System.out.println("Fee=" + Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
        final Wallet.SendResult sendResult = w.sendCoins(getKit().peerGroup(), tpfaucetAddress, amountToSend);
        checkNotNull(sendResult); // We should never try to send more coins
        // than
        // we have!
        System.out.println("Sending ...");
        // Register a callback that is invoked when the transaction has
        // propagated across the network.
        // This shows a second style of registering ListenableFuture
        // callbacks,
        // it works when you don't
        // need access to the object the future returns.
        sendResult.broadcastComplete.addListener(new Runnable() {
            public void run() {
                // The wallet has changed now, it'll get auto saved shortly
                // or
                // when the app shuts down.
                System.out
                        .println("Sent coins onwards! Transaction hash is " + sendResult.tx.getHashAsString());
            }
        }, MoreExecutors.sameThreadExecutor());

    } catch (WrongNetworkException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (AddressFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.elasticsearch.threadpool.client.ClientThreadPool.java

public ClientThreadPool(Settings settings) {
    this.settings = settings;

    Map<String, Settings> groupSettings = settings.getGroups("threadpool");

    Map<String, ExecutorHolder> executors = Maps.newHashMap();
    executors.put(Names.GENERIC, build(Names.GENERIC, "cached", groupSettings.get(Names.GENERIC),
            settingsBuilder().put("keep_alive", "30s").build()));
    executors.put(Names.SAME, new ExecutorHolder(MoreExecutors.sameThreadExecutor(),
            new ClientThreadPoolInfoElement(Names.SAME, "same")));
    this.executors = ImmutableMap.copyOf(executors);
    this.scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1,
            ClientEsExecutors.daemonThreadFactory(settings, "scheduler"));
    this.scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    this.scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);

    //TimeValue estimatedTimeInterval = componentSettings.getAsTime("estimated_time_interval", TimeValue.timeValueMillis(200));
    TimeValue estimatedTimeInterval = TimeValue.timeValueMillis(200);
    this.estimatedTimeThread = new EstimatedTimeThread(ClientEsExecutors.threadName(settings, "[timer]"),
            estimatedTimeInterval.millis());
    this.estimatedTimeThread.start();
}

From source file:com.helion3.prism.api.parameters.ParameterPlayer.java

@Override
public Optional<ListenableFuture<?>> process(QuerySession session, String parameter, String value,
        Query query) {//from  w  w w  .  j a  v a2  s .c  o m
    ListenableFuture<GameProfile> profile = Prism.getGame().getServer().getGameProfileManager().get(value,
            true);

    profile.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                query.addCondition(FieldCondition.of(DataQueries.Player, MatchRule.EQUALS,
                        profile.get().getUniqueId().toString()));
            } catch (InterruptedException | ExecutionException e) {
                session.getCommandSource().get()
                        .sendMessage(Format.error(String.format("Cannot find profile for user \"%s\"", value)));
                e.printStackTrace();
            }
        }
    }, MoreExecutors.sameThreadExecutor());

    return Optional.of(profile);
}

From source file:org.apache.brooklyn.policy.AbstractInvokeEffectorPolicy.java

/**
 * Invoke effector with parameters on the entity that the policy is attached to.
 *///from  w  ww  .j a  v a2  s  .c om
protected <T> Task<T> invoke(Effector<T> effector, Map<String, ?> parameters) {
    if (isBusySensorEnabled()) {
        getTaskCounter().incrementAndGet();
        publishIsBusy();
    }
    Task<T> task = entity.invoke(effector, parameters);
    if (isBusySensorEnabled()) {
        task.addListener(new EffectorListener(), MoreExecutors.sameThreadExecutor());
    }
    return task;
}