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

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

Introduction

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

Prototype

public static Executor directExecutor() 

Source Link

Document

Returns an Executor that runs each task in the thread that invokes Executor#execute execute , as in CallerRunsPolicy .

Usage

From source file:org.dcache.restful.policyengine.MigrationPolicyEngine.java

public void adjust() throws InterruptedException, CacheException, NoRouteToCellException {

    Collection<String> targetPools = getTargetPolls(fileAttributes, cellStub);
    Collection<String> sourcePools = getSourcePools(fileAttributes);

    if (sourcePools.isEmpty()) {
        throw new CacheException("No file locations found");
    }//from  www. jav a  2s . c o m
    if (targetPools.isEmpty()) {
        throw new InternalError("No HSM pool found");
    }

    List<String> samePools = targetPools.stream().filter(n -> sourcePools.contains(n))
            .collect(Collectors.toList());

    boolean isOnHsmPool = !samePools.isEmpty();

    if (fileAttributes.getStorageInfo().locations().isEmpty() || !isOnHsmPool) {

        String sourcePool = isOnHsmPool ? samePools.get(0) : getRandomPool(sourcePools);

        String target = isOnHsmPool ? samePools.get(0) : getRandomPool(targetPools);

        PoolSelectionUnit.SelectionPool pool = poolMonitor.getPoolSelectionUnit().getPool(target);
        PoolMigrationCopyReplicaMessage poolMigrationCopyReplicaMessage = new PoolMigrationCopyReplicaMessage(
                uuid, sourcePool, fileAttributes, replicaState, stickyRecords, false, false, null, false);

        CellStub.addCallback(
                cellStub.send(new CellPath(pool.getAddress()), poolMigrationCopyReplicaMessage,
                        CellEndpoint.SendFlag.RETRY_ON_NO_ROUTE_TO_CELL),
                new AbstractMessageCallback<PoolMigrationCopyReplicaMessage>() {

                    @Override
                    public void success(PoolMigrationCopyReplicaMessage message) {
                    }

                    @Override
                    public void timeout(String message) {
                    }

                    @Override
                    public void failure(int rc, Object error) {
                    }
                }, MoreExecutors.directExecutor());
    }
}

From source file:com.facebook.buck.distributed.build_client.RacingBuildPhase.java

private static void attachMostBuildRulesCompletedCallback(LocalBuildRunner racingBuildExecutor,
        RemoteBuildRuleCompletionWaiter remoteBuildRuleCompletionWaiter) {
    Futures.addCallback(remoteBuildRuleCompletionWaiter.waitForMostBuildRulesToFinishRemotely(),
            new FutureCallback<Boolean>() {
                @Override/*from  ww w .j  a  v a 2 s.com*/
                public void onSuccess(@Nullable Boolean result) {
                    racingBuildExecutor.getBuildPhaseLatch().countDown();
                }

                @Override
                public void onFailure(Throwable t) {
                    LOG.error(t, "Received exception in most build rules finished event handler.");
                }
            }, MoreExecutors.directExecutor());
}

From source file:org.openqa.selenium.safari.WebSocketConnection.java

/**
 * Sends a text frame./* w w w  .j a v  a  2s .  c  o  m*/
 *
 * @param data The frame data.
 * @return A future that will resolve with a response from the driver.
 * @throws IllegalStateException If the underlying connection is closed or if there is
 *     already a pending response.
 */
public ListenableFuture<String> send(String data) {
    checkChannel();

    final SettableFuture<String> response = SettableFuture.create();
    response.addListener(new Runnable() {
        @Override
        public void run() {
            pendingResponse.compareAndSet(response, null);
        }
    }, MoreExecutors.directExecutor());

    if (pendingResponse.compareAndSet(null, response)) {
        TextWebSocketFrame frame = new TextWebSocketFrame(data);
        channel.write(frame).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    response.setException(future.getCause());
                }
            }
        });
        return response;
    }

    throw new IllegalStateException("Currently awaiting a response to a previous message");
}

From source file:io.v.v23.InputChannels.java

/**
 * Iterates over all elements in {@code channel}, invoking {@link InputChannelCallback#onNext}
 * method on the provided callback for each element.
 * <p>//  ww  w . ja  va2 s  . c o  m
 * Returns a new {@link ListenableFuture} that completes when the provided {@link InputChannel}
 * has exhausted all of its elements or has encountered an error.
 * <p>
 * The returned future and all the callbacks will be executed on a
 * {@link MoreExecutors#directExecutor() direct executor}.
 */
@CheckReturnValue
public static <T> ListenableFuture<Void> withCallback(InputChannel<T> channel,
        InputChannelCallback<? super T> callback) {
    return withCallback(channel, callback, MoreExecutors.directExecutor());
}

From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java

public ListenableFuture<T> read(Identifier id) {
    ListenableFuture<ResultSet> rs = submitRead(id);
    return Futures.transformAsync(rs, new AsyncFunction<ResultSet, T>() {
        @Override//  www .  ja v  a2  s .  c  o  m
        public ListenableFuture<T> apply(ResultSet result) {
            if (result.isExhausted()) {
                return Futures.immediateFailedFuture(new ItemNotFoundException(id.toString()));
            }

            return Futures.immediateFuture(marshalRow(result.one()));
        }
    }, MoreExecutors.directExecutor());
}

From source file:us.hgk.rhythm.exp.sextetsinputtest.Main.java

private PacketWriterService createPacketWriter(String host, int port) {
    PacketWriterService writer = new TcpPacketWriterService(this, host, port);
    writer.addListener(createMutualStopListener("TcpPacketWriterService"), MoreExecutors.directExecutor());
    return writer;
}

From source file:org.bugkillers.bus.eventbus.EventBus_.java

/**
 * Creates a new EventBus with the given {@link SubscriberExceptionHandler}.
 *
 * @param exceptionHandler Handler for subscriber exceptions.
 * @since 16.0/*w w  w  . java  2s . co m*/
 */
public EventBus_(SubscriberExceptionHandler_ exceptionHandler) {
    this("default", MoreExecutors.directExecutor(), Dispatcher_.perThreadDispatchQueue(), exceptionHandler);
}

From source file:org.opendaylight.controller.clustering.it.provider.impl.PrefixShardHandler.java

public ListenableFuture<RpcResult<Void>> onCreatePrefixShard(final CreatePrefixShardInput input) {

    final SettableFuture<RpcResult<Void>> future = SettableFuture.create();

    final CompletionStage<DistributedShardRegistration> completionStage;
    final YangInstanceIdentifier identifier = serializer.toYangInstanceIdentifier(input.getPrefix());

    try {/*ww  w .  jav a 2s.  c o m*/
        completionStage = shardFactory.createDistributedShard(
                new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, identifier),
                input.getReplicas().stream().map(MemberName::forName).collect(Collectors.toList()));

        completionStage.thenAccept(registration -> {
            LOG.debug("Shard[{}] created successfully.", identifier);
            registrations.put(identifier, registration);

            final ListenableFuture<Void> ensureFuture = ensureListExists();
            Futures.addCallback(ensureFuture, new FutureCallback<Void>() {
                @Override
                public void onSuccess(@Nullable final Void result) {
                    LOG.debug("Initial list write successful.");
                    future.set(RpcResultBuilder.<Void>success().build());
                }

                @Override
                public void onFailure(final Throwable throwable) {
                    LOG.warn("Shard[{}] creation failed:", identifier, throwable);

                    final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION,
                            "create-shard-failed", "Shard creation failed", "cluster-test-app", "", throwable);
                    future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
                }
            }, MoreExecutors.directExecutor());
        });
        completionStage.exceptionally(throwable -> {
            LOG.warn("Shard[{}] creation failed:", identifier, throwable);

            final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION,
                    "create-shard-failed", "Shard creation failed", "cluster-test-app", "", throwable);
            future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
            return null;
        });
    } catch (final DOMDataTreeShardingConflictException e) {
        LOG.warn("Unable to register shard for: {}.", identifier);

        final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "create-shard-failed",
                "Sharding conflict", "cluster-test-app", "", e);
        future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
    }

    return future;
}

From source file:com.navercorp.nbasearc.gcp.GatewayConnectionPool.java

private SettableFuture<?> closeEventLoops(SettableFuture<?> previousCloseJob) {
    final SettableFuture<?> future = SettableFuture.create();
    previousCloseJob.addListener(new Runnable() {
        @Override/*from w  w w.  j a va 2  s  . c  o  m*/
        public void run() {
            eventLoopTrunk.close().addListener(new Runnable() {
                @Override
                public void run() {
                    future.set(null);
                }
            }, MoreExecutors.directExecutor());
        }
    }, MoreExecutors.directExecutor());
    return future;
}

From source file:org.bitcoinj.examples.ForwardingService.java

private static void forwardCoins(Transaction tx) {
    try {/*from   w w w  .  j a va  2s.c o m*/
        Coin value = tx.getValueSentToMe(kit.wallet());
        System.out.println("Forwarding " + value.toFriendlyString());
        // Now send the coins back! Send with a small fee attached to ensure rapid confirmation.
        final Coin amountToSend = value.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
        final Wallet.SendResult sendResult = kit.wallet().sendCoins(kit.peerGroup(), forwardingAddress,
                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() {
            @Override
            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.directExecutor());
    } catch (KeyCrypterException | InsufficientMoneyException e) {
        // We don't use encrypted wallets in this example - can never happen.
        throw new RuntimeException(e);
    }
}