當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。