當前位置: 首頁>>代碼示例>>Java>>正文


Java Futures類代碼示例

本文整理匯總了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;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:24,代碼來源:DOMDataBrokerTransactionChainImpl.java

示例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;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:17,代碼來源:BindingDOMTransactionChainAdapter.java

示例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);
    }
}
 
開發者ID:identiv,項目名稱:ts-cards,代碼行數:19,代碼來源:SmartcardIoTransmitter.java

示例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));
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:19,代碼來源:GetConstantService.java

示例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);
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:17,代碼來源:GuavaLFReturnValueHandlerTest.java

示例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;
}
 
開發者ID:lemonJun,項目名稱:TakinRPC,代碼行數:29,代碼來源:Leader.java

示例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());
        }
    };
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:21,代碼來源:RpcBrokerTest.java

示例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);
        }
    });

}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:21,代碼來源:EventSourceTopology.java

示例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);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:20,代碼來源:ConcurrentDOMDataBroker.java

示例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());
}
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:26,代碼來源:ECKeyTest.java

示例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());
    }
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:20,代碼來源:ServerCommands.java

示例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( );
}
 
開發者ID:u2032,項目名稱:wall-t,代碼行數:17,代碼來源:ApiControllerTest.java

示例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());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:32,代碼來源:PingPongTransactionChain.java

示例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;
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:25,代碼來源:DefaultOvsdbClient.java

示例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);
        }
    });
}
 
開發者ID:guodroid,項目名稱:okwallet,代碼行數:20,代碼來源:PaymentChannelClientState.java


注:本文中的com.google.common.util.concurrent.Futures類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。