本文整理匯總了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);
}
示例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;
}
示例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());
}
示例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);
}
示例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());
}
示例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));
}
示例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());
}
示例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");
}
}
示例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();
}
示例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());
}
示例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;
}
示例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);
}
});
}
示例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);
}
示例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));
}
示例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);
}
}