当前位置: 首页>>代码示例>>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;未经允许,请勿转载。