本文整理匯總了Java中com.google.common.util.concurrent.Futures類的典型用法代碼示例。如果您正苦於以下問題:Java Futures類的具體用法?Java Futures怎麽用?Java Futures使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Futures類屬於com.google.common.util.concurrent包,在下文中一共展示了Futures類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: submit
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Override
public CheckedFuture<Void, TransactionCommitFailedException> submit(
final DOMDataWriteTransaction transaction, final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
checkNotFailed();
checkNotClosed();
final CheckedFuture<Void, TransactionCommitFailedException> ret = broker.submit(transaction, cohorts);
COUNTER_UPDATER.incrementAndGet(this);
Futures.addCallback(ret, new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
transactionCompleted();
}
@Override
public void onFailure(final Throwable t) {
transactionFailed(transaction, t);
}
});
return ret;
}
示例2: listenForFailure
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
private CheckedFuture<Void, TransactionCommitFailedException> listenForFailure(
final WriteTransaction tx, final CheckedFuture<Void, TransactionCommitFailedException> future) {
Futures.addCallback(future, new FutureCallback<Void>() {
@Override
public void onFailure(final Throwable t) {
failTransactionChain(tx,t);
}
@Override
public void onSuccess(final Void result) {
// Intentionally NOOP
}
});
return future;
}
示例3: apply
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Override
public ListenableFuture<ApduResponse> apply(byte[] in) {
// how to actually transmit to the card
// here we just use the normal transmit stuff
try {
ByteBuffer command = ByteBuffer.wrap(in);
ByteBuffer response = ByteBuffer.allocate(1024); // TODO is this reasonable?
int size = card.getBasicChannel().transmit(command, response);
byte[] out = new byte[size];
System.arraycopy(response.array(), 0,
out, 0, size);
return Futures.immediateFuture(new ApduResponse(out));
} catch (CardException e) {
throw new RuntimeException(e);
}
}
示例4: invokeRpc
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Nonnull
@Override
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final DOMRpcIdentifier rpc,
@Nullable final NormalizedNode<?, ?> input) {
LOG.debug("get-constant invoked, current value: {}", constant);
final LeafNode<Object> value = ImmutableLeafNodeBuilder.create()
.withNodeIdentifier(new NodeIdentifier(CONSTANT))
.withValue(constant)
.build();
final ContainerNode result = ImmutableContainerNodeBuilder.create()
.withNodeIdentifier(new NodeIdentifier(OUTPUT))
.withChild(value)
.build();
return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(result));
}
示例5: handlesFailure
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Test
public void handlesFailure() throws Exception {
final AtomicReference<Object> value = new AtomicReference<>();
Exception ex = new Exception("This is bad");
ListenableFuture<String> future = Futures.immediateFailedFuture(ex);
GuavaLFReturnValueHandler handler = new GuavaLFReturnValueHandler() {
@Override
protected void startDeferredResultProcessing(ModelAndViewContainer mavContainer, NativeWebRequest webRequest, DeferredResult<Object> deferredResult) throws Exception {
value.set(deferredResult.getResult());
}
};
handler.handleReturnValue(future, null, null, null);
assertThat(value.get()).isEqualTo(ex);
}
示例6: sendRequests
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
/**
* Notify the {@link ReplicaManager} to send an update the next possible time it can
*
* @return futures with the result of the update
*/
@Nonnull
@VisibleForTesting
List<ListenableFuture<AppendEntriesResponse>> sendRequests(final RaftStateContext ctx) {
List<ListenableFuture<AppendEntriesResponse>> responses = newArrayList();
for (ReplicaManager replicaManager : managers.values()) {
ListenableFuture<AppendEntriesResponse> response = replicaManager.requestUpdate();
responses.add(response);
Futures.addCallback(response, new FutureCallback<AppendEntriesResponse>() {
@Override
public void onSuccess(@Nullable AppendEntriesResponse result) {
updateCommitted();
checkTermOnResponse(ctx, result);
}
@Override
public void onFailure(Throwable t) {
}
});
}
return responses;
}
示例7: testExecuteRpc
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Test
public void testExecuteRpc() {
new JavaTestKit(node1) {
{
final ContainerNode invokeRpcResult = makeRPCOutput("bar");
final DOMRpcResult rpcResult = new DefaultDOMRpcResult(invokeRpcResult);
when(domRpcService1.invokeRpc(eq(TEST_RPC_TYPE), Mockito.<NormalizedNode<?, ?>>any())).thenReturn(
Futures.<DOMRpcResult, DOMRpcException>immediateCheckedFuture(rpcResult));
final ExecuteRpc executeMsg = ExecuteRpc.from(TEST_RPC_ID, null);
rpcInvoker1.tell(executeMsg, getRef());
final RpcResponse rpcResponse = expectMsgClass(duration("5 seconds"), RpcResponse.class);
assertEquals(rpcResult.getResult(), rpcResponse.getResultNormalizedNode());
}
};
}
示例8: putData
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
private <T extends DataObject> void putData(final LogicalDatastoreType store,
final InstanceIdentifier<T> path,
final T data){
final WriteTransaction tx = getDataBroker().newWriteOnlyTransaction();
tx.put(store, path, data, true);
Futures.addCallback( tx.submit(), new FutureCallback<Void>(){
@Override
public void onSuccess(final Void result) {
LOG.trace("Data has put into datastore {} {}", store, path);
}
@Override
public void onFailure(final Throwable t) {
LOG.error("Can not put data into datastore [store: {}] [path: {}] [exception: {}]",store,path, t);
}
});
}
示例9: submit
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Override
protected CheckedFuture<Void, TransactionCommitFailedException> submit(final DOMDataWriteTransaction transaction,
final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
Preconditions.checkArgument(cohorts != null, "Cohorts must not be null.");
LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
if (cohorts.isEmpty()) {
return Futures.immediateCheckedFuture(null);
}
final AsyncNotifyingSettableFuture clientSubmitFuture =
new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
doCanCommit(clientSubmitFuture, transaction, cohorts);
return MappingCheckedFuture.create(clientSubmitFuture, COMMIT_ERROR_MAPPER);
}
示例10: testSValue
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Test
public void testSValue() throws Exception {
// Check that we never generate an S value that is larger than half the curve order. This avoids a malleability
// issue that can allow someone to change a transaction [hash] without invalidating the signature.
final int ITERATIONS = 10;
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(ITERATIONS));
List<ListenableFuture<ECKey.ECDSASignature>> sigFutures = Lists.newArrayList();
final ECKey key = new ECKey();
for (byte i = 0; i < ITERATIONS; i++) {
final byte[] hash = HashUtil.sha3(new byte[]{i});
sigFutures.add(executor.submit(new Callable<ECKey.ECDSASignature>() {
@Override
public ECKey.ECDSASignature call() throws Exception {
return key.doSign(hash);
}
}));
}
List<ECKey.ECDSASignature> sigs = Futures.allAsList(sigFutures).get();
for (ECKey.ECDSASignature signature : sigs) {
assertTrue(signature.s.compareTo(ECKey.HALF_CURVE_ORDER) <= 0);
}
final ECKey.ECDSASignature duplicate = new ECKey.ECDSASignature(sigs.get(0).r, sigs.get(0).s);
assertEquals(sigs.get(0), duplicate);
assertEquals(sigs.get(0).hashCode(), duplicate.hashCode());
}
示例11: hub
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Command(
aliases = {"hub", "lobby"},
desc = "Teleport to the lobby"
)
public void hub(final CommandContext args, CommandSender sender) throws CommandException {
if(sender instanceof ProxiedPlayer) {
final ProxiedPlayer player = (ProxiedPlayer) sender;
final Server server = Futures.getUnchecked(executor.submit(() -> serverTracker.byPlayer(player)));
if(server.role() == ServerDoc.Role.LOBBY || server.role() == ServerDoc.Role.PGM) {
// If Bukkit server is running Commons, let it handle the command
throw new CommandBypassException();
}
player.connect(proxy.getServerInfo("default"));
player.sendMessage(new ComponentBuilder("Teleporting you to the lobby").color(ChatColor.GREEN).create());
} else {
sender.sendMessage(new ComponentBuilder("Only players may use this command").color(ChatColor.RED).create());
}
}
示例12: loadProjectList_callback_registers_exception_on_ack_future
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Test
public void loadProjectList_callback_registers_exception_on_ack_future( ) throws Exception {
// Setup
when( _mockRequestController.sendRequest( getApiVersion( ), "projects", ProjectList.class ) )
.thenReturn( Futures.immediateFailedFuture( new RuntimeException( "Unexpected test exception" ) ) );
// Exercise
final ListenableFuture<Void> ackFuture = _apiController.loadProjectList( );
// Verify
try {
ackFuture.get( );
} catch ( ExecutionException e ) {
if ( e.getCause( ).getClass( ) == RuntimeException.class && e.getCause( ).getMessage( ).equals( "Unexpected test exception" ) )
return;
}
TestCase.fail( );
}
示例13: processTransaction
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
/**
* Process a ready transaction. The caller needs to ensure that
* each transaction is seen only once by this method.
*
* @param tx Transaction which needs processing.
*/
@GuardedBy("this")
private void processTransaction(@Nonnull final PingPongTransaction tx) {
if (failed) {
LOG.debug("Cancelling transaction {}", tx);
tx.getTransaction().cancel();
return;
}
LOG.debug("Submitting transaction {}", tx);
if (!INFLIGHT_UPDATER.compareAndSet(this, null, tx)) {
LOG.warn("Submitting transaction {} while {} is still running", tx, inflightTx);
}
Futures.addCallback(tx.getTransaction().submit(), new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
transactionSuccessful(tx, result);
}
@Override
public void onFailure(final Throwable t) {
transactionFailed(tx, t);
}
}, MoreExecutors.directExecutor());
}
示例14: transactConfig
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
@Override
public ListenableFuture<List<OperationResult>> transactConfig(String dbName,
List<Operation> operations) {
if (dbName == null) {
return null;
}
DatabaseSchema dbSchema = schema.get(dbName);
if (dbSchema != null) {
Function<List<JsonNode>, List<OperationResult>> rowFunction = (input -> {
log.info("Get ovsdb operation result");
List<OperationResult> result = FromJsonUtil
.jsonNodeToOperationResult(input, operations);
if (result == null) {
log.debug("The operation result is null");
return null;
}
return result;
});
return Futures.transform(transact(dbSchema, operations),
rowFunction);
}
return null;
}
示例15: watchCloseConfirmations
import com.google.common.util.concurrent.Futures; //導入依賴的package包/類
protected void watchCloseConfirmations() {
// When we see the close transaction get enough confirmations, we can just delete the record
// of this channel along with the refund tx from the wallet, because we're not going to need
// any of that any more.
final TransactionConfidence confidence = storedChannel.close.getConfidence();
int numConfirms = Context.get().getEventHorizon();
ListenableFuture<TransactionConfidence> future = confidence.getDepthFuture(numConfirms, Threading.SAME_THREAD);
Futures.addCallback(future, new FutureCallback<TransactionConfidence>() {
@Override
public void onSuccess(TransactionConfidence result) {
deleteChannelFromWallet();
}
@Override
public void onFailure(Throwable t) {
Throwables.propagate(t);
}
});
}