当前位置: 首页>>代码示例>>Java>>正文


Java ListenableFuture类代码示例

本文整理汇总了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();
}
 
开发者ID:talentchain,项目名称:talchain,代码行数:25,代码来源:Eth62.java

示例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;
  });
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:17,代码来源:JpaAttributeDao.java

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

}
 
开发者ID:lemonJun,项目名称:TakinRPC,代码行数:21,代码来源:Client.java

示例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;
  });
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:18,代码来源:JpaAttributeDao.java

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

}
 
开发者ID:novarto-oss,项目名称:sane-dbc,代码行数:17,代码来源:SanityTest.java

示例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());
}
 
开发者ID:xtianus,项目名称:yadaframework,代码行数:31,代码来源:YadaJobScheduler.java

示例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);
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:11,代码来源:CassandraDeviceTypeDao.java

示例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));
}
 
开发者ID:nsg-ethz,项目名称:iTAP-controller,代码行数:27,代码来源:OFConnectionTest.java

示例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)));
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:17,代码来源:ClusterAdminRpcService.java

示例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 ) );
}
 
开发者ID:u2032,项目名称:wall-t,代码行数:19,代码来源:ApiControllerTest.java

示例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;
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:22,代码来源:BlobIndices.java

示例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;
}
 
开发者ID:guodroid,项目名称:okwallet,代码行数:39,代码来源:Peer.java

示例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( ) );
}
 
开发者ID:u2032,项目名称:wall-t,代码行数:11,代码来源:ConfigurationViewModel.java

示例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()));
    }
  }));
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:13,代码来源:PluginProcessingContext.java

示例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 );
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:16,代码来源:AbstractBaseDataModel.java


注:本文中的com.google.common.util.concurrent.ListenableFuture类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。