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