本文整理匯總了Java中com.google.common.util.concurrent.ListenableFuture類的典型用法代碼示例。如果您正苦於以下問題:Java ListenableFuture類的具體用法?Java ListenableFuture怎麽用?Java ListenableFuture使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ListenableFuture類屬於com.google.common.util.concurrent包,在下文中一共展示了ListenableFuture類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: sendGetBlockHeaders
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Override
public synchronized ListenableFuture<List<BlockHeader>> sendGetBlockHeaders(long blockNumber, int maxBlocksAsk, boolean reverse) {
if (ethState == EthState.STATUS_SUCCEEDED && peerState != IDLE) return null;
if(logger.isTraceEnabled()) logger.trace(
"Peer {}: queue GetBlockHeaders, blockNumber [{}], maxBlocksAsk [{}]",
channel.getPeerIdShort(),
blockNumber,
maxBlocksAsk
);
if (headerRequest != null) {
throw new RuntimeException("The peer is waiting for headers response: " + this);
}
GetBlockHeadersMessage headersRequest = new GetBlockHeadersMessage(blockNumber, null, maxBlocksAsk, 0, reverse);
GetBlockHeadersMessageWrapper messageWrapper = new GetBlockHeadersMessageWrapper(headersRequest);
headerRequest = messageWrapper;
sendNextHeaderRequest();
return messageWrapper.getFutureHeaders();
}
示例2: removeAll
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Override
public ListenableFuture<List<Void>> removeAll(EntityId entityId, String attributeType, List<String> keys) {
List<AttributeKvEntity> entitiesToDelete = keys.stream().map(key -> {
AttributeKvEntity entityToDelete = new AttributeKvEntity();
entityToDelete.setEntityType(entityId.getEntityType());
entityToDelete.setEntityId(fromTimeUUID(entityId.getId()));
entityToDelete.setAttributeType(attributeType);
entityToDelete.setAttributeKey(key);
return entityToDelete;
}).collect(Collectors.toList());
return service.submit(() -> {
attributeKvRepository.delete(entitiesToDelete);
return null;
});
}
示例3: requestVote
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Nonnull
public ListenableFuture<RequestVoteResponse> requestVote(@Nonnull
final Replica replica, @Nonnull
final RequestVote request) {
checkNotNull(replica);
checkNotNull(request);
// Put a (possibly) blocking connect onto a different thread
ListenableFuture<ListenableFuture<RequestVoteResponse>> response = networkCallExecutor.submit(new Callable<ListenableFuture<RequestVoteResponse>>() {
@Override
public ListenableFuture<RequestVoteResponse> call() throws Exception {
RaftClient client = clientProvider.get(replica);
return client.requestVote(request);
}
});
// Transfer the response back onto the raft thread
return transform(response, Identity.<RequestVoteResponse> identity(), raftExecutor);
}
示例4: save
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Override
public ListenableFuture<Void> save(EntityId entityId, String attributeType, AttributeKvEntry attribute) {
AttributeKvEntity entity = new AttributeKvEntity();
entity.setEntityType(entityId.getEntityType());
entity.setEntityId(fromTimeUUID(entityId.getId()));
entity.setAttributeType(attributeType);
entity.setAttributeKey(attribute.getKey());
entity.setLastUpdateTs(attribute.getLastUpdateTs());
entity.setStrValue(attribute.getStrValue().orElse(null));
entity.setDoubleValue(attribute.getDoubleValue().orElse(null));
entity.setLongValue(attribute.getLongValue().orElse(null));
entity.setBooleanValue(attribute.getBooleanValue().orElse(null));
return service.submit(() -> {
attributeKvRepository.save(entity);
return null;
});
}
示例5: sanity
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Test public void sanity()
{
ListenableFuture<Integer> success = dbAsync.submit(DB.unit(42));
SQLException ex = new SQLException("failed i have");
ListenableFuture<Integer> fail = dbAsync.submit(DB.db((Try1<Connection, Integer, SQLException>) c ->
{
assertThat(c, is(notNullValue()));
throw ex;
}));
assertThat(awaitAndGet(success), is(42));
assertThat(awaitAndGetFailure(fail), is(ex));
}
示例6: runJob
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
/**
* Run the job now.
* The job must set its own state to DISABLED or PAUSED when failed, otherwise it is set to ACTIVE.
* @param yadaJob
* @return
*/
public void runJob(Long yadaJobId) {
log.debug("Running job id {}", yadaJobId);
YadaJob toRun = yadaJobRepository.findOne(yadaJobId);
if (toRun==null) {
log.info("Job not found when trying to run it, id={}", toRun);
return;
}
yadaJobRepository.internalSetRunning(yadaJobId, YadaJobState.RUNNING.toId(), YadaJobState.ACTIVE.toId());
final YadaJob wiredYadaJob = (YadaJob) yadaUtil.autowire(toRun); // YadaJob instances can have @Autowire fields
ListenableFuture<Void> jobHandle = jobScheduler.submit(wiredYadaJob);
jobHandles.put(yadaJobId, jobHandle);
Futures.addCallback(jobHandle, new FutureCallback<Void>() {
// The callback is run in executor
public void onSuccess(Void result) {
// result is always null
jobHandles.remove(yadaJobId);
yadaJobSchedulerDao.internalJobSuccessful(wiredYadaJob);
}
public void onFailure(Throwable thrown) {
jobHandles.remove(yadaJobId);
yadaJobSchedulerDao.internalJobFailed(wiredYadaJob, thrown);
}
}, MoreExecutors.directExecutor());
}
示例7: findDeviceTypesByTenantIdCustomerIdAndIdsAsync
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Override
public ListenableFuture<List<DeviceType>> findDeviceTypesByTenantIdCustomerIdAndIdsAsync(UUID tenantId, UUID customerId, List<UUID> deviceIds) {
log.debug("Try to find devices by tenantId [{}], customerId [{}] and device Ids [{}]", tenantId, customerId, deviceIds);
Select select = select().from(getColumnFamilyName());
Select.Where query = select.where();
query.and(eq(DEVICE_TYPE_TENANT_ID_PROPERTY, tenantId));
query.and(eq(DEVICE_TYPE_CUSTOMER_ID_PROPERTY, customerId));
query.and(in(ID_PROPERTY, deviceIds));
return findListByStatementAsync(query);
}
示例8: testWriteRequestSuccess
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Test(timeout = 5000)
public void testWriteRequestSuccess() throws InterruptedException, ExecutionException {
Capture<List<OFMessage>> cMsgList = prepareChannelForWriteList();
OFEchoRequest echoRequest = factory.echoRequest(new byte[] {});
ListenableFuture<OFEchoReply> future = conn.writeRequest(echoRequest);
assertThat("Connection should have 1 pending request",
conn.getPendingRequestIds().size(), equalTo(1));
assertThat("Should have captured MsgList", cMsgList.getValue(),
Matchers.<OFMessage> contains(echoRequest));
assertThat("Future should not be complete yet", future.isDone(), equalTo(false));
OFEchoReply echoReply = factory.buildEchoReply()
.setXid(echoRequest.getXid())
.build();
assertThat("Connection should have accepted the response",
conn.deliverResponse(echoReply),
equalTo(true));
assertThat("Future should be complete ", future.isDone(), equalTo(true));
assertThat(future.get(), equalTo(echoReply));
assertThat("Connection should have no pending requests",
conn.getPendingRequestIds().isEmpty(), equalTo(true));
}
示例9: sendMessageToManagerForConfiguredShards
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
private <T> void sendMessageToManagerForConfiguredShards(DataStoreType dataStoreType,
List<Entry<ListenableFuture<T>, ShardResultBuilder>> shardResultData,
Function<String, Object> messageSupplier) {
ActorContext actorContext = dataStoreType == DataStoreType.Config ? configDataStore.getActorContext()
: operDataStore.getActorContext();
Set<String> allShardNames = actorContext.getConfiguration().getAllShardNames();
LOG.debug("Sending message to all shards {} for data store {}", allShardNames, actorContext.getDataStoreName());
for (String shardName: allShardNames) {
ListenableFuture<T> future = this.ask(actorContext.getShardManager(), messageSupplier.apply(shardName),
SHARD_MGR_TIMEOUT);
shardResultData.add(new SimpleEntry<>(future,
new ShardResultBuilder().setShardName(shardName).setDataStoreType(dataStoreType)));
}
}
示例10: loadBuildTypeList_callback_registers_project_to_BuildTypeManager_and_dispatch_it_on_event_bus
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Test
public void loadBuildTypeList_callback_registers_project_to_BuildTypeManager_and_dispatch_it_on_event_bus( ) throws Exception {
// Setup
final BuildTypeList buildTypelist = new BuildTypeList( );
buildTypelist.addBuildType( new BuildType( "bt1", "btName", "btProjectName", "btProjectId" ) );
buildTypelist.addBuildType( new BuildType( "bt2", "btName", "btProjectName", "btProjectId" ) );
when( _mockRequestController.sendRequest( getApiVersion( ), "buildTypes", BuildTypeList.class ) )
.thenReturn( Futures.immediateFuture( buildTypelist ) );
// Exercise
final ListenableFuture<Void> ackFuture = _apiController.loadBuildTypeList( );
// Verify
assertThat( _buildTypeManager.getBuildTypes( ).size( ), is( 2 ) );
assertThat( _buildTypeManager.getBuildTypes( ).get( 0 ).getId( ), is( "bt1" ) );
assertThat( _buildTypeManager.getBuildTypes( ).get( 1 ).getId( ), is( "bt2" ) );
assertThat( _dispatchedObjects, hasItem( _buildTypeManager ) );
assertThat( ackFuture.isDone( ), is( true ) );
}
示例11: createBlobTable
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
public ListenableFuture<Void> createBlobTable(String tableName,
Settings indexSettings) {
Settings.Builder builder = Settings.builder();
builder.put(indexSettings);
builder.put(SETTING_INDEX_BLOBS_ENABLED, true);
final SettableFuture<Void> result = SettableFuture.create();
transportCreateIndexActionProvider.get().execute(new CreateIndexRequest(fullIndexName(tableName), builder.build()), new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse createIndexResponse) {
assert createIndexResponse.isAcknowledged();
result.set(null);
}
@Override
public void onFailure(Throwable e) {
result.setException(e);
}
});
return result;
}
示例12: downloadDependencies
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
/**
* <p>Returns a future that wraps a list of all transactions that the given transaction depends on, recursively.
* Only transactions in peers memory pools are included; the recursion stops at transactions that are in the
* current best chain. So it doesn't make much sense to provide a tx that was already in the best chain and
* a precondition checks this.</p>
*
* <p>For example, if tx has 2 inputs that connect to transactions A and B, and transaction B is unconfirmed and
* has one input connecting to transaction C that is unconfirmed, and transaction C connects to transaction D
* that is in the chain, then this method will return either {B, C} or {C, B}. No ordering is guaranteed.</p>
*
* <p>This method is useful for apps that want to learn about how long an unconfirmed transaction might take
* to confirm, by checking for unexpectedly time locked transactions, unusually deep dependency trees or fee-paying
* transactions that depend on unconfirmed free transactions.</p>
*
* <p>Note that dependencies downloaded this way will not trigger the onTransaction method of event listeners.</p>
*/
public ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx) {
TransactionConfidence.ConfidenceType txConfidence = tx.getConfidence().getConfidenceType();
Preconditions.checkArgument(txConfidence != TransactionConfidence.ConfidenceType.BUILDING);
log.info("{}: Downloading dependencies of {}", getAddress(), tx.getHashAsString());
final LinkedList<Transaction> results = new LinkedList<>();
// future will be invoked when the entire dependency tree has been walked and the results compiled.
final ListenableFuture<Object> future = downloadDependenciesInternal(vDownloadTxDependencyDepth, 0, tx,
new Object(), results);
final SettableFuture<List<Transaction>> resultFuture = SettableFuture.create();
Futures.addCallback(future, new FutureCallback<Object>() {
@Override
public void onSuccess(Object ignored) {
resultFuture.set(results);
}
@Override
public void onFailure(Throwable throwable) {
resultFuture.setException(throwable);
}
});
return resultFuture;
}
示例13: requestLoadingBuilds
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
void requestLoadingBuilds( ) {
_loading.setValue( true );
_loadingFailure.setValue( true );
_loadingInformation.setValue( "Trying to connect..." );
final ListenableFuture<Void> loadProjectsFuture = _apiController.loadProjectList( );
final ListenableFuture<Void> loadBuildTypesfuture = transform( loadProjectsFuture, (AsyncFunction<Void, Void>) input -> _apiController.loadBuildTypeList( ) );
addCallback( loadBuildTypesfuture, loadingSuccessfulCallback( ) );
}
示例14: removeAttributes
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
@Override
public void removeAttributes(final TenantId tenantId, final EntityId entityId, final String scope,
final List<String> keys, final PluginCallback<Void> callback) {
validate(entityId, new ValidationCallback(callback, ctx -> {
ListenableFuture<List<Void>> futures = pluginCtx.attributesService.removeAll(entityId, scope, keys);
Futures.addCallback(futures, getCallback(callback, v -> null), executor);
if (entityId.getEntityType() == ThingType.DEVICE) {
onDeviceAttributesDeleted(tenantId, new DeviceId(entityId.getId()),
keys.stream().map(key -> new AttributeKey(scope, key)).collect(Collectors.toSet()));
}
}));
}
示例15: disposeSubscription
import com.google.common.util.concurrent.ListenableFuture; //導入依賴的package包/類
protected synchronized ListenableFuture<Void> disposeSubscription ( final DefaultSubscription subscription )
{
this.subscriptions.remove ( subscription );
this.numberOfSubscriptions = this.subscriptions.size ();
if ( this.executor.isShutdown () )
{
// if we are already disposed
return Futures.immediateFuture ( null );
}
// the completion will come from the executor, so the completion has to wait in line
// with possible remaining updated
return this.executor.submit ( () -> null );
}