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


Java SettableFuture類代碼示例

本文整理匯總了Java中com.google.common.util.concurrent.SettableFuture的典型用法代碼示例。如果您正苦於以下問題:Java SettableFuture類的具體用法?Java SettableFuture怎麽用?Java SettableFuture使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


SettableFuture類屬於com.google.common.util.concurrent包,在下文中一共展示了SettableFuture類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: createIndexAndExecuteUpsertRequest

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
private void createIndexAndExecuteUpsertRequest(final UpsertByIdNode.Item item,
                                                final SettableFuture<TaskResult> futureResult) {
    transportCreateIndexAction.execute(
            new CreateIndexRequest(item.index()).cause("upsert single item"),
            new ActionListener<CreateIndexResponse>() {
        @Override
        public void onResponse(CreateIndexResponse createIndexResponse) {
            executeUpsertRequest(item, futureResult);
        }

        @Override
        public void onFailure(Throwable e) {
            e = ExceptionsHelper.unwrapCause(e);
            if (e instanceof IndexAlreadyExistsException) {
                executeUpsertRequest(item, futureResult);
            } else {
                futureResult.setException(e);
            }

        }
    });
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:23,代碼來源:UpsertByIdTask.java

示例2: externalMiner_shouldWork

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
@Test
    public void externalMiner_shouldWork() throws Exception {

        final Block startBestBlock = bc.getBlockchain().getBestBlock();

        final SettableFuture<MinerIfc.MiningResult> futureBlock = SettableFuture.create();

        blockMiner.setExternalMiner(new MinerIfc() {
            @Override
            public ListenableFuture<MiningResult> mine(Block block) {
//                System.out.print("Mining requested");
                return futureBlock;
            }

            @Override
            public boolean validate(BlockHeader blockHeader) {
                return true;
            }
        });
        Block b = bc.getBlockchain().createNewBlock(startBestBlock, EMPTY_LIST, EMPTY_LIST);
        Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mineLight(b).get();
        futureBlock.set(new MinerIfc.MiningResult(ByteUtil.byteArrayToLong(b.getNonce()), b.getMixHash(), b));

        assertThat(bc.getBlockchain().getBestBlock().getNumber(), is(startBestBlock.getNumber() + 1));
    }
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:26,代碼來源:ExternalMinerTest.java

示例3: read

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
                                                                               final YangInstanceIdentifier path) {
    checkState(root != null, "A modify operation (put, merge or delete) must be performed prior to a read operation");
    final SettableFuture<Optional<NormalizedNode<?, ?>>> readResult = SettableFuture.create();
    final Queue<Modification> currentHistory = Lists.newLinkedList(modificationHistoryMap.get(store));
    Futures.addCallback(initialReadMap.get(store), new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
        @Override
        public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) {
            final DataTreeModification mod = snapshotMap.get(store).newModification();
            if (result.isPresent()) {
                mod.write(path, result.get());
            }
            applyModificationHistoryToSnapshot(mod, currentHistory);
            readResult.set(mod.readNode(path));
        }

        @Override
        public void onFailure(final Throwable t) {
            readResult.setException(t);
        }
    }, MoreExecutors.directExecutor());

    return Futures.makeChecked(readResult, ReadFailedException.MAPPER);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:26,代碼來源:ShardedDOMDataBrokerDelegatingReadWriteTransaction.java

示例4: ListenableFutureConversionSuccess

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
/**
 * Test the conversion of successful {@link Future} to {@link RedFuture}
 * through {@link RedFuture#convert(Future)}
 */
@Test
public void ListenableFutureConversionSuccess() throws Throwable {
    AtomicBoolean reachedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFailureBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFinallyBlock = new AtomicBoolean(false);
    AtomicBoolean reachedTypedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean correctValueReturned = new AtomicBoolean(false);
    SettableFuture<String> settableFuture = SettableFuture.create();
    RedFutureOf<String> redFuture = RedFuture.convert(settableFuture);
    redFuture.addSuccessCallback(() -> reachedSuccessBlock.set(true));
    redFuture.addSuccessCallback(s -> {
        reachedTypedSuccessBlock.set(true);
        correctValueReturned.set(s.equals("test"));
    });
    redFuture.addFinallyCallback(() -> reachedFinallyBlock.set(true));
    redFuture.addFailureCallback(throwable -> reachedFailureBlock.set(true));
    settableFuture.set("test");
    Thread.sleep(VALIDATION_SLEEP_TIME);
    Assert.assertTrue(reachedFinallyBlock.get());
    Assert.assertTrue(reachedSuccessBlock.get());
    Assert.assertTrue(reachedTypedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
}
 
開發者ID:avivcarmis,項目名稱:java-red,代碼行數:28,代碼來源:TestRedFuture.java

示例5: validate

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
@Override
public ListenableFuture<Boolean> validate() {
    LOG.debug("Validating transaction for shard {}", shardRoot);

    checkTransactionReadied();
    final List<ListenableFuture<Boolean>> futures =
            cohorts.stream().map(DOMStoreThreePhaseCommitCohort::canCommit).collect(Collectors.toList());
    final SettableFuture<Boolean> ret = SettableFuture.create();

    Futures.addCallback(Futures.allAsList(futures), new FutureCallback<List<Boolean>>() {
        @Override
        public void onSuccess(final List<Boolean> result) {
            ret.set(true);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            ret.setException(throwable);
        }
    }, MoreExecutors.directExecutor());

    return ret;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:24,代碼來源:ShardProxyTransaction.java

示例6: getSource

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
@Override
public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(SourceIdentifier sourceIdentifier) {
    LOG.trace("Getting yang schema source for {}", sourceIdentifier.getName());

    Future<YangTextSchemaSourceSerializationProxy> result = remoteRepo.getYangTextSchemaSource(sourceIdentifier);

    final SettableFuture<YangTextSchemaSource> res = SettableFuture.create();
    result.onComplete(new OnComplete<YangTextSchemaSourceSerializationProxy>() {
        @Override
        public void onComplete(Throwable throwable,
                YangTextSchemaSourceSerializationProxy yangTextSchemaSourceSerializationProxy) {
            if (yangTextSchemaSourceSerializationProxy != null) {
                res.set(yangTextSchemaSourceSerializationProxy.getRepresentation());
            }
            if (throwable != null) {
                res.setException(throwable);
            }
        }

    }, executionContext);

    return Futures.makeChecked(res, MAPPER);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:24,代碼來源:RemoteSchemaProvider.java

示例7: createAckFunction

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
private Ack createAckFunction(final SettableFuture<GenericOutcome> future) {
    return new Ack() {
        @Override
        public void call(Object... objects) {
            if (objects.length == 0 || objects[0] == null) {
                future.set(new GenericOutcome(new GameLiftError(GameLiftErrorType.SERVICE_CALL_FAILED)));
            }

            boolean value = (boolean) objects[0];

            if (value) {
                future.set(new GenericOutcome());
            } else {
                future.set(new GenericOutcome(new GameLiftError(GameLiftErrorType.SERVICE_CALL_FAILED)));
            }
        }
    };
}
 
開發者ID:BoxtrotStudio,項目名稱:amazon-gamelift-serversdk-java,代碼行數:19,代碼來源:AuxProxyMessageSender.java

示例8: ESDeleteTask

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
public ESDeleteTask(UUID jobId,
                    ESDeleteNode node,
                    TransportDeleteAction transport,
                    JobContextService jobContextService) {
    super(jobId, node.executionPhaseId(), node.docKeys().size(), jobContextService);
    List<DeleteRequest> requests = new ArrayList<>(node.docKeys().size());
    List<ActionListener> listeners = new ArrayList<>(node.docKeys().size());
    for (DocKeys.DocKey docKey : node.docKeys()) {
        DeleteRequest request = new DeleteRequest(
                ESGetTask.indexName(node.tableInfo(), docKey.partitionValues()),
                Constants.DEFAULT_MAPPING_TYPE, docKey.id());
        request.routing(docKey.routing());
        if (docKey.version().isPresent()) {
            request.version(docKey.version().get());
        }
        requests.add(request);
        SettableFuture<TaskResult> result = SettableFuture.create();
        results.add(result);
        listeners.add(new DeleteResponseListener(result));
    }

    createContext("delete", requests, listeners, transport, null);
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:24,代碼來源:ESDeleteTask.java

示例9: receivePaymentAck

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
private void receivePaymentAck(Protos.PaymentAck paymentAck) {
    SettableFuture<PaymentIncrementAck> future;
    Coin value;

    lock.lock();
    try {
        if (increasePaymentFuture == null) return;
        checkNotNull(increasePaymentFuture, "Server sent a PAYMENT_ACK with no outstanding payment");
        log.info("Received a PAYMENT_ACK from the server");
        future = increasePaymentFuture;
        value = lastPaymentActualAmount;
    } finally {
        lock.unlock();
    }

    // Ensure the future runs without the client lock held.
    future.set(new PaymentIncrementAck(value, paymentAck.getInfo()));
}
 
開發者ID:creativechain,項目名稱:creacoinj,代碼行數:19,代碼來源:PaymentChannelClient.java

示例10: ESClusterUpdateSettingsTask

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
public ESClusterUpdateSettingsTask(UUID jobId,
                                   TransportClusterUpdateSettingsAction transport,
                                   ESClusterUpdateSettingsNode node) {
    super(jobId);
    this.transport = transport;

    final SettableFuture<TaskResult> result = SettableFuture.create();
    results = Collections.<ListenableFuture<TaskResult>>singletonList(result);

    request = new ClusterUpdateSettingsRequest();
    request.persistentSettings(node.persistentSettings());
    request.transientSettings(node.transientSettings());
    if (node.persistentSettingsToRemove() != null) {
        request.persistentSettingsToRemove(node.persistentSettingsToRemove());
    }
    if (node.transientSettingsToRemove() != null) {
        request.transientSettingsToRemove(node.transientSettingsToRemove());
    }
    listener = ActionListeners.wrap(result, Functions.constant(TaskResult.ONE_ROW));
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:21,代碼來源:ESClusterUpdateSettingsTask.java

示例11: getUTXOs

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
/**
 * Sends a query to the remote peer asking for the unspent transaction outputs (UTXOs) for the given outpoints.
 * The result should be treated only as a hint: it's possible for the returned outputs to be fictional and not
 * exist in any transaction, and it's possible for them to be spent the moment after the query returns.
 * <b>Most peers do not support this request. You will need to connect to Bitcoin XT peers if you want
 * this to work.</b>
 *
 * @param includeMempool If true (the default) the results take into account the contents of the memory pool too.
 * @throws ProtocolException if this peer doesn't support the protocol.
 */
public ListenableFuture<UTXOsMessage> getUTXOs(List<TransactionOutPoint> outPoints, boolean includeMempool) {
    lock.lock();
    try {
        VersionMessage peerVer = getPeerVersionMessage();
        if (peerVer.clientVersion < GetUTXOsMessage.MIN_PROTOCOL_VERSION)
            throw new ProtocolException("Peer does not support getutxos protocol version");
        if ((peerVer.localServices & GetUTXOsMessage.SERVICE_FLAGS_REQUIRED) != GetUTXOsMessage.SERVICE_FLAGS_REQUIRED)
            throw new ProtocolException("Peer does not support getutxos protocol flag: find Bitcoin XT nodes.");
        SettableFuture<UTXOsMessage> future = SettableFuture.create();
        // Add to the list of in flight requests.
        if (getutxoFutures == null)
            getutxoFutures = new LinkedList<>();
        getutxoFutures.add(future);
        sendMessage(new GetUTXOsMessage(params, outPoints, includeMempool));
        return future;
    } finally {
        lock.unlock();
    }
}
 
開發者ID:creativechain,項目名稱:creacoinj,代碼行數:30,代碼來源:Peer.java

示例12: backupDatastore

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
@Override
public Future<RpcResult<Void>> backupDatastore(final BackupDatastoreInput input) {
    LOG.debug("backupDatastore: {}", input);

    if (Strings.isNullOrEmpty(input.getFilePath())) {
        return newFailedRpcResultFuture("A valid file path must be specified");
    }

    final SettableFuture<RpcResult<Void>> returnFuture = SettableFuture.create();
    ListenableFuture<List<DatastoreSnapshot>> future = sendMessageToShardManagers(GetSnapshot.INSTANCE);
    Futures.addCallback(future, new FutureCallback<List<DatastoreSnapshot>>() {
        @Override
        public void onSuccess(List<DatastoreSnapshot> snapshots) {
            saveSnapshotsToFile(new DatastoreSnapshotList(snapshots), input.getFilePath(), returnFuture);
        }

        @Override
        public void onFailure(Throwable failure) {
            onDatastoreBackupFailure(input.getFilePath(), returnFuture, failure);
        }
    }, MoreExecutors.directExecutor());

    return returnFuture;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:25,代碼來源:ClusterAdminRpcService.java

示例13: deleteNode

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
@Override
protected ListenableFuture<Boolean> deleteNode(String path, boolean deleteChildrenIfNecessary) {
  final SettableFuture<Boolean> future = SettableFuture.create();
  boolean ret = true;
  if (FileUtils.isFileExists(path)) {
    if (!deleteChildrenIfNecessary && FileUtils.hasChildren(path)) {
      LOG.severe("delete called on a path with children but deleteChildrenIfNecessary is false: "
          + path);
      ret = false;
    } else {
      ret = FileUtils.deleteFile(path);
    }
  }
  future.set(ret);

  return future;
}
 
開發者ID:DSC-SPIDAL,項目名稱:twister2,代碼行數:18,代碼來源:SharedFileSystemStateManager.java

示例14: createResource

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
@Override
public BatchAccount createResource(BatchAccounts resources) throws Exception {
    final String batchAccountName = "batch" + this.testId;
    final BatchAccount[] batchAccounts = new BatchAccount[1];
    final SettableFuture<BatchAccount> future = SettableFuture.create();


    Observable<Indexable> resourceStream = resources.define(batchAccountName)
            .withRegion(Region.INDIA_CENTRAL)
            .withNewResourceGroup()
            .withTag("mytag", "testtag")
            .createAsync();

    Utils.<BatchAccount>rootResource(resourceStream)
            .subscribe(new Action1<BatchAccount>() {
                @Override
                public void call(BatchAccount batchAccount) {
                    future.set(batchAccount);
                }
            });

    batchAccounts[0] = future.get();
    Assert.assertNull(batchAccounts[0].autoStorage());

    return batchAccounts[0];
}
 
開發者ID:Azure,項目名稱:azure-libraries-for-java,代碼行數:27,代碼來源:TestBatch.java

示例15: visitRevokePrivilegeAnalyzedStatement

import com.google.common.util.concurrent.SettableFuture; //導入依賴的package包/類
@Override
public ListenableFuture<Long> visitRevokePrivilegeAnalyzedStatement(RevokePrivilegeAnalyzedStatement analysis, SingleJobTask jobId) {
    String tableName = analysis.getTable();
    boolean isDBPrivilege = true;
    if (tableName.contains(".")) {
        isDBPrivilege = false;
    }
    GrantOrRevokeUserPrivilegeRequest grantRequest = new GrantOrRevokeUserPrivilegeRequest(analysis.getUsername(),
            tableName, PrivilegeType.valueOf(analysis.getPrivilege().toUpperCase()),
            isDBPrivilege, false);
    grantRequest.putHeader(LoginUserContext.USER_INFO_KEY, analysis.getParameterContext().getLoginUserContext());
    final SettableFuture<Long> future = SettableFuture.create();
    ActionListener<GrantOrRevokeUserPrivilegeResponse> listener = ActionListeners.wrap(future, Functions.<Long>constant(ONE));
    transportActionProvider.transportGrantOrRevokeUserPrivilegeAction().execute(grantRequest, listener);
    return future;
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:17,代碼來源:DDLStatementDispatcher.java


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