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


Java Future类代码示例

本文整理汇总了Java中scala.concurrent.Future的典型用法代码示例。如果您正苦于以下问题:Java Future类的具体用法?Java Future怎么用?Java Future使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Future类属于scala.concurrent包,在下文中一共展示了Future类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: verifyActorReady

import scala.concurrent.Future; //导入依赖的package包/类
@SuppressWarnings("checkstyle:IllegalCatch")
private void verifyActorReady(ActorRef actorRef) {
    // Sometimes we see messages go to dead letters soon after creation - it seems the actor isn't quite
    // in a state yet to receive messages or isn't actually created yet. This seems to happen with
    // actorSelection so, to alleviate it, we use an actorSelection and send an Identify message with
    // retries to ensure it's ready.

    Timeout timeout = new Timeout(100, TimeUnit.MILLISECONDS);
    Throwable lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
        try {
            ActorSelection actorSelection = system.actorSelection(actorRef.path().toString());
            Future<Object> future = Patterns.ask(actorSelection, new Identify(""), timeout);
            ActorIdentity reply = (ActorIdentity)Await.result(future, timeout.duration());
            Assert.assertNotNull("Identify returned null", reply.getRef());
            return;
        } catch (Exception | AssertionError e) {
            Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
            lastError = e;
        }
    }

    throw new RuntimeException(lastError);
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:26,代码来源:TestActorFactory.java

示例2: verifyShardState

import scala.concurrent.Future; //导入依赖的package包/类
public static void verifyShardState(final AbstractDataStore datastore, final String shardName,
        final Consumer<OnDemandShardState> verifier) throws Exception {
    ActorContext actorContext = datastore.getActorContext();

    Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
    ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));

    AssertionError lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
        OnDemandShardState shardState = (OnDemandShardState)actorContext
                .executeOperation(shardActor, GetOnDemandRaftState.INSTANCE);

        try {
            verifier.accept(shardState);
            return;
        } catch (AssertionError e) {
            lastError = e;
            Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        }
    }

    throw lastError;
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:25,代码来源:IntegrationTestKit.java

示例3: tryCreateTransaction

import scala.concurrent.Future; //导入依赖的package包/类
/**
  Performs a CreateTransaction try async.
 */
private void tryCreateTransaction() {
    LOG.debug("Tx {} Primary shard {} found - trying create transaction", getIdentifier(),
            primaryShardInfo.getPrimaryShardActor());

    Object serializedCreateMessage = new CreateTransaction(getIdentifier(), getTransactionType().ordinal(),
                primaryShardInfo.getPrimaryShardVersion()).toSerializable();

    Future<Object> createTxFuture = getActorContext().executeOperationAsync(
            primaryShardInfo.getPrimaryShardActor(), serializedCreateMessage, createTxMessageTimeout);

    createTxFuture.onComplete(new OnComplete<Object>() {
        @Override
        public void onComplete(Throwable failure, Object response) {
            onCreateTransactionComplete(failure, response);
        }
    }, getActorContext().getClientDispatcher());
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:21,代码来源:RemoteTransactionContextSupport.java

示例4: responseType

import scala.concurrent.Future; //导入依赖的package包/类
@Test public void responseType() {
  Type bodyClass = new TypeToken<Future<String>>() {}.getType();
  assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type bodyWildcard = new TypeToken<Future<? extends String>>() {}.getType();
  assertThat(factory.get(bodyWildcard, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type bodyGeneric = new TypeToken<Future<List<String>>>() {}.getType();
  assertThat(factory.get(bodyGeneric, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(new TypeToken<List<String>>() {}.getType());
  Type responseClass = new TypeToken<Future<Response<String>>>() {}.getType();
  assertThat(factory.get(responseClass, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type responseWildcard = new TypeToken<Future<Response<? extends String>>>() {}.getType();
  assertThat(factory.get(responseWildcard, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type resultClass = new TypeToken<Future<Response<String>>>() {}.getType();
  assertThat(factory.get(resultClass, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type resultWildcard = new TypeToken<Future<Response<? extends String>>>() {}.getType();
  assertThat(factory.get(resultWildcard, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:24,代码来源:ScalaCallAdapterFactoryTest.java

示例5: performRegistration

import scala.concurrent.Future; //导入依赖的package包/类
private synchronized void performRegistration(ActorRef shard) {
    if (isClosed()) {
        return;
    }
    cohortRegistry = shard;
    Future<Object> future =
            Patterns.ask(shard, new DataTreeCohortActorRegistry.RegisterCohort(subtree, actor), TIMEOUT);
    future.onComplete(new OnComplete<Object>() {

        @Override
        public void onComplete(Throwable failure, Object val) {
            if (failure != null) {
                LOG.error("Unable to register {} as commit cohort", getInstance(), failure);
            }
            if (isClosed()) {
                removeRegistration();
            }
        }

    }, actorContext.getClientDispatcher());
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:22,代码来源:DataTreeCohortRegistrationProxy.java

示例6: testNegativeReadWithReadOnlyTransactionClosed

import scala.concurrent.Future; //导入依赖的package包/类
@Test(expected = ReadFailedException.class)
public void testNegativeReadWithReadOnlyTransactionClosed() throws Exception {

    final ActorRef shard = createShard();
    final Props props = ShardTransaction.props(RO, STORE.newReadOnlyTransaction(nextTransactionId()), shard,
            datastoreContext, shardStats);

    final TestActorRef<ShardTransaction> subject = TestActorRef.create(getSystem(), props,
            "testNegativeReadWithReadOnlyTransactionClosed");

    Future<Object> future = akka.pattern.Patterns.ask(subject,
            new ReadData(YangInstanceIdentifier.EMPTY, DataStoreVersions.CURRENT_VERSION), 3000);
    Await.result(future, Duration.create(3, TimeUnit.SECONDS));

    subject.underlyingActor().getDOMStoreTransaction().abortFromTransactionActor();

    future = akka.pattern.Patterns.ask(subject, new ReadData(YangInstanceIdentifier.EMPTY,
            DataStoreVersions.CURRENT_VERSION), 3000);
    Await.result(future, Duration.create(3, TimeUnit.SECONDS));
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:21,代码来源:ShardTransactionFailureTest.java

示例7: doRegistration

import scala.concurrent.Future; //导入依赖的package包/类
private void doRegistration(ActorRef shard, final YangInstanceIdentifier path,
        DataChangeScope scope) {

    Future<Object> future = actorContext.executeOperationAsync(shard,
            new RegisterChangeListener(path, dataChangeListenerActor, scope,
                listener instanceof ClusteredDOMDataChangeListener),
            actorContext.getDatastoreContext().getShardInitializationTimeout());

    future.onComplete(new OnComplete<Object>() {
        @Override
        public void onComplete(Throwable failure, Object result) {
            if (failure != null) {
                LOG.error("Failed to register DataChangeListener {} at path {}",
                        listener, path.toString(), failure);
            } else {
                RegisterDataTreeNotificationListenerReply reply = (RegisterDataTreeNotificationListenerReply)result;
                setListenerRegistrationActor(actorContext.actorSelection(
                        reply.getListenerRegistrationPath()));
            }
        }
    }, actorContext.getClientDispatcher());
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:23,代码来源:DataChangeListenerRegistrationProxy.java

示例8: cancelJob

import scala.concurrent.Future; //导入依赖的package包/类
public void cancelJob(JobID jobId) throws Exception {
    // this needs better support in the Flink Mini Cluster
    if (getCurrentlyRunningJobsJava().contains(jobId)) {
        final FiniteDuration timeout = timeout();
        final ActorGateway jobManagerGateway = getLeaderGateway(timeout);

        Future<Object> cancelFuture = jobManagerGateway.ask(
                new JobManagerMessages.CancelJob(jobId), timeout);

        Object result = Await.result(cancelFuture, timeout);
        if (!(result instanceof JobManagerMessages.CancellationSuccess)) {
            throw new Exception("Cancellation failed");
        }
    } else {
        throw new IllegalStateException("Job is not running");
    }
}
 
开发者ID:pravega,项目名称:flink-connectors,代码行数:18,代码来源:FlinkMiniClusterWithSavepointCommand.java

示例9: readyTransaction

import scala.concurrent.Future; //导入依赖的package包/类
Future<ActorSelection> readyTransaction() {
    // avoid the creation of a promise and a TransactionOperation
    if (transactionContext != null) {
        return transactionContext.readyTransaction();
    }

    final Promise<ActorSelection> promise = Futures.promise();
    enqueueTransactionOperation(new TransactionOperation() {
        @Override
        public void invoke(TransactionContext newTransactionContext) {
            promise.completeWith(newTransactionContext.readyTransaction());
        }
    });

    return promise.future();
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:17,代码来源:TransactionContextWrapper.java

示例10: doAsyncReadHighestSequenceNr

import scala.concurrent.Future; //导入依赖的package包/类
@Override
public Future<Long> doAsyncReadHighestSequenceNr(String persistenceId, long fromSequenceNr) {
    return Futures.future(() -> {
        if (log.isDebugEnabled()) {
            log.debug("doAsyncReadHighestSequenceNr '{}' - {}", persistenceId, fromSequenceNr);
        }
        if (sequenceNumberTrack.containsKey(persistenceId)) {
            long highestSequenceNr = sequenceNumberTrack.get(persistenceId);
            if (highestSequenceNr != 0) {
                if (log.isDebugEnabled()) {
                    log.debug("doAsyncReadHighestSequenceNr '{}' {} -> {}", persistenceId, fromSequenceNr, highestSequenceNr);
                }
                return highestSequenceNr;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("doAsyncReadHighestSequenceNr '{}' {} -> {}", persistenceId, fromSequenceNr, fromSequenceNr);
                }
                return fromSequenceNr;
            }
        }
        return fromSequenceNr;
    }, storage.getDispatcher());
}
 
开发者ID:Romeh,项目名称:akka-persistance-ignite,代码行数:24,代码来源:IgniteWriteJournal.java

示例11: initiateDirectCommit

import scala.concurrent.Future; //导入依赖的package包/类
Future<Object> initiateDirectCommit() {
    final Future<Object> messageFuture = initiateCommit(true);
    messageFuture.onComplete(new OnComplete<Object>() {
        @Override
        public void onComplete(final Throwable failure, final Object message) throws Throwable {
            if (failure != null) {
                LOG.error("Failed to prepare transaction {} on backend", transaction.getIdentifier(), failure);
                transactionAborted(transaction);
            } else if (CommitTransactionReply.isSerializedType(message)) {
                LOG.debug("Transaction {} committed successfully", transaction.getIdentifier());
                transactionCommitted(transaction);
            } else {
                LOG.error("Transaction {} resulted in unhandled message type {}, aborting", message.getClass());
                transactionAborted(transaction);
            }
        }
    }, actorContext.getClientDispatcher());

    return messageFuture;
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:21,代码来源:LocalThreePhaseCommitCohort.java

示例12: doLoadAsync

import scala.concurrent.Future; //导入依赖的package包/类
@Override
public Future<Optional<SelectedSnapshot>> doLoadAsync(String persistenceId, SnapshotSelectionCriteria criteria) {
    return storage.execute(persistenceId, cache, (entityIdParam, cacheParam) -> {
        if (log.isDebugEnabled()) {
            log.debug("doLoadAsync '{}' {} {}", persistenceId, criteria.minSequenceNr(), criteria.toString());
        }
        try (QueryCursor<Cache.Entry<Long, SnapshotItem>> query = cache
                .query(new SqlQuery<Long, SnapshotItem>(SnapshotItem.class, "sequenceNr >= ? AND sequenceNr <= ? AND timestamp >= ? AND timestamp <= ? and persistenceId=?")
                        .setArgs(criteria.minSequenceNr(), criteria.maxSequenceNr(), criteria.minTimestamp(), criteria.maxTimestamp(), persistenceId))) {

            List<Cache.Entry<Long, SnapshotItem>> iterator = query.getAll();
            final Optional<Cache.Entry<Long, SnapshotItem>> max = iterator.stream().max((o1, o2) -> {
                if (o1.getValue().getSequenceNr() > o2.getValue().getSequenceNr()) {
                    return 1;
                } else if (o1.getValue().getTimestamp() > o2.getValue().getTimestamp()) {
                    return 1;
                } else {
                    return -1;
                }
            });
            return Optional.ofNullable(max.isPresent() ? convert(persistenceId, max.get().getValue()) : null);
        }
    });
}
 
开发者ID:Romeh,项目名称:akka-persistance-ignite,代码行数:25,代码来源:IgniteSnapshotStore.java

示例13: start

import scala.concurrent.Future; //导入依赖的package包/类
public static DistributedEntityOwnershipService start(final ActorContext context,
        final EntityOwnerSelectionStrategyConfig strategyConfig) {
    ActorRef shardManagerActor = context.getShardManager();

    Configuration configuration = context.getConfiguration();
    Collection<MemberName> entityOwnersMemberNames = configuration.getUniqueMemberNamesForAllShards();
    CreateShard createShard = new CreateShard(new ModuleShardConfiguration(EntityOwners.QNAME.getNamespace(),
            "entity-owners", ENTITY_OWNERSHIP_SHARD_NAME, ModuleShardStrategy.NAME, entityOwnersMemberNames),
                    newShardBuilder(context, strategyConfig), null);

    Future<Object> createFuture = context.executeOperationAsync(shardManagerActor,
            createShard, MESSAGE_TIMEOUT);

    createFuture.onComplete(new OnComplete<Object>() {
        @Override
        public void onComplete(final Throwable failure, final Object response) {
            if (failure != null) {
                LOG.error("Failed to create {} shard", ENTITY_OWNERSHIP_SHARD_NAME, failure);
            } else {
                LOG.info("Successfully created {} shard", ENTITY_OWNERSHIP_SHARD_NAME);
            }
        }
    }, context.getClientDispatcher());

    return new DistributedEntityOwnershipService(context);
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:27,代码来源:DistributedEntityOwnershipService.java

示例14: testPersistentActorWIthIgnite

import scala.concurrent.Future; //导入依赖的package包/类
@Test
public void testPersistentActorWIthIgnite() throws Exception {
    ActorRef actorRef = actorSystem.actorOf(Props.create(IgnitePersistentTestActor.class, "1"));
    actorRef.tell("+a", ActorRef.noSender());
    actorRef.tell("+b", ActorRef.noSender());
    actorRef.tell("+c", ActorRef.noSender());
    actorRef.tell("throw", ActorRef.noSender());

    Future<Object> future = Patterns.ask(actorRef, "-b", 1000);
    Await.result(future, Duration.create(1, TimeUnit.SECONDS));

    IgniteCache<Object, Object> cache = ignite.getOrCreateCache("akka-journal");
    Assert.assertEquals(cache.size(), 4);

    actorSystem.actorSelection("akka://test/user/**").tell("!!!", ActorRef.noSender());

    Await.result(actorSystem.terminate(), Duration.create(1, TimeUnit.SECONDS));
}
 
开发者ID:Romeh,项目名称:akka-persistance-ignite,代码行数:19,代码来源:IgniteJournalCacheTest.java

示例15: executeLocalEntityOwnershipShardOperation

import scala.concurrent.Future; //导入依赖的package包/类
@VisibleForTesting
void executeLocalEntityOwnershipShardOperation(final Object message) {
    if (localEntityOwnershipShard == null) {
        Future<ActorRef> future = context.findLocalShardAsync(ENTITY_OWNERSHIP_SHARD_NAME);
        future.onComplete(new OnComplete<ActorRef>() {
            @Override
            public void onComplete(final Throwable failure, final ActorRef shardActor) {
                if (failure != null) {
                    LOG.error("Failed to find local {} shard", ENTITY_OWNERSHIP_SHARD_NAME, failure);
                } else {
                    localEntityOwnershipShard = shardActor;
                    executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
                }
            }
        }, context.getClientDispatcher());

    } else {
        executeEntityOwnershipShardOperation(localEntityOwnershipShard, message);
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:21,代码来源:DistributedEntityOwnershipService.java


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