本文整理匯總了Java中akka.util.Timeout類的典型用法代碼示例。如果您正苦於以下問題:Java Timeout類的具體用法?Java Timeout怎麽用?Java Timeout使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Timeout類屬於akka.util包,在下文中一共展示了Timeout類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: verifyActorReady
import akka.util.Timeout; //導入依賴的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: waitUntilLeader
import akka.util.Timeout; //導入依賴的package包/類
@SuppressWarnings("checkstyle:IllegalCatch")
public static void waitUntilLeader(ActorRef actorRef) {
FiniteDuration duration = Duration.create(100, TimeUnit.MILLISECONDS);
for (int i = 0; i < 20 * 5; i++) {
Future<Object> future = Patterns.ask(actorRef, FindLeader.INSTANCE, new Timeout(duration));
try {
final Optional<String> maybeLeader = ((FindLeaderReply)Await.result(future, duration)).getLeaderActor();
if (maybeLeader.isPresent()) {
return;
}
} catch (Exception e) {
LOG.error("FindLeader failed", e);
}
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
}
Assert.fail("Leader not found for actorRef " + actorRef.path());
}
示例3: getListenerActorsInfo
import akka.util.Timeout; //導入依賴的package包/類
@SuppressWarnings("checkstyle:IllegalCatch")
private List<DataTreeListenerInfo> getListenerActorsInfo(Collection<ActorSelection> actors) {
final Timeout timeout = new Timeout(20, TimeUnit.SECONDS);
final List<Future<Object>> futureList = new ArrayList<>(actors.size());
for (ActorSelection actor: actors) {
futureList.add(Patterns.ask(actor, GetInfo.INSTANCE, timeout));
}
try {
final List<DataTreeListenerInfo> listenerInfoList = new ArrayList<>();
Await.result(Futures.sequence(futureList, ExecutionContext.Implicits$.MODULE$.global()),
timeout.duration()).forEach(obj -> listenerInfoList.add((DataTreeListenerInfo) obj));
return listenerInfoList;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
示例4: RemoteTransactionContextSupport
import akka.util.Timeout; //導入依賴的package包/類
RemoteTransactionContextSupport(final TransactionContextWrapper transactionContextWrapper,
final TransactionProxy parent, final String shardName) {
this.parent = Preconditions.checkNotNull(parent);
this.shardName = shardName;
this.transactionContextWrapper = transactionContextWrapper;
// For the total create tx timeout, use 2 times the election timeout. This should be enough time for
// a leader re-election to occur if we happen to hit it in transition.
totalCreateTxTimeout = parent.getActorContext().getDatastoreContext().getShardRaftConfig()
.getElectionTimeOutInterval().toMillis() * 2;
// We'll use the operationTimeout for the the create Tx message timeout so it can be set appropriately
// for unit tests but cap it at MAX_CREATE_TX_MSG_TIMEOUT_IN_MS. The operationTimeout could be set
// larger than the totalCreateTxTimeout in production which we don't want.
long operationTimeout = parent.getActorContext().getOperationTimeout().duration().toMillis();
createTxMessageTimeout = new Timeout(Math.min(operationTimeout, MAX_CREATE_TX_MSG_TIMEOUT_IN_MS),
TimeUnit.MILLISECONDS);
}
示例5: findPrimary
import akka.util.Timeout; //導入依賴的package包/類
private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
.getShardInitializationTimeout().duration().$times(2));
Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
futureObj.onComplete(new OnComplete<Object>() {
@Override
public void onComplete(final Throwable failure, final Object response) {
if (failure != null) {
handler.onFailure(failure);
} else {
if (response instanceof RemotePrimaryShardFound) {
handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
} else if (response instanceof LocalPrimaryShardFound) {
handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
} else {
handler.onUnknownResponse(response);
}
}
}
}, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
}
示例6: verifyRaftState
import akka.util.Timeout; //導入依賴的package包/類
static void verifyRaftState(final TestActorRef<? extends EntityOwnershipShard> shard,
Consumer<OnDemandRaftState> verifier)
throws Exception {
AssertionError lastError = null;
Stopwatch sw = Stopwatch.createStarted();
while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS);
Future<Object> future = Patterns.ask(shard, GetOnDemandRaftState.INSTANCE, new Timeout(operationDuration));
OnDemandRaftState raftState = (OnDemandRaftState)Await.result(future, operationDuration);
try {
verifier.accept(raftState);
return;
} catch (AssertionError e) {
lastError = e;
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
}
}
throw lastError;
}
示例7: setUp
import akka.util.Timeout; //導入依賴的package包/類
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
schemaContext = TestModel.createTestContext();
doReturn(getSystem()).when(mockActorContext).getActorSystem();
doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
doReturn(new ShardStrategyFactory(configuration,
LogicalDatastoreType.CONFIGURATION)).when(mockActorContext).getShardStrategyFactory();
doReturn(schemaContext).when(mockActorContext).getSchemaContext();
doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
final ClientIdentifier mockClientId = MockIdentifiers.clientIdentifier(getClass(), memberName);
mockComponentFactory = new TransactionContextFactory(mockActorContext, mockClientId);
Timer timer = new MetricRegistry().timer("test");
doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
}
示例8: setupActorContextWithInitialCreateTransaction
import akka.util.Timeout; //導入依賴的package包/類
protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
final TransactionType type, final short transactionVersion, final String prefix,
final ActorRef shardActorRef) {
ActorRef txActorRef;
if (type == TransactionType.WRITE_ONLY
&& dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
txActorRef = shardActorRef;
} else {
txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
log.info("Created mock shard Tx actor {}", txActorRef);
doReturn(actorSystem.actorSelection(txActorRef.path()))
.when(mockActorContext).actorSelection(txActorRef.path().toString());
doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext)
.executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
eqCreateTransaction(prefix, type), any(Timeout.class));
}
return txActorRef;
}
示例9: testExceptionOnInitialCreateTransaction
import akka.util.Timeout; //導入依賴的package包/類
private void testExceptionOnInitialCreateTransaction(final Exception exToThrow, final Invoker invoker)
throws Exception {
ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
if (exToThrow instanceof PrimaryNotFoundException) {
doReturn(Futures.failed(exToThrow)).when(mockActorContext).findPrimaryShardAsync(anyString());
} else {
doReturn(primaryShardInfoReply(getSystem(), actorRef)).when(mockActorContext)
.findPrimaryShardAsync(anyString());
}
doReturn(Futures.failed(exToThrow)).when(mockActorContext).executeOperationAsync(
any(ActorSelection.class), any(), any(Timeout.class));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
propagateReadFailedExceptionCause(invoker.invoke(transactionProxy));
}
示例10: testInvalidCreateTransactionReply
import akka.util.Timeout; //導入依賴的package包/類
@Test(expected = IllegalArgumentException.class)
public void testInvalidCreateTransactionReply() throws Exception {
ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
doReturn(getSystem().actorSelection(actorRef.path())).when(mockActorContext)
.actorSelection(actorRef.path().toString());
doReturn(primaryShardInfoReply(getSystem(), actorRef)).when(mockActorContext)
.findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
doReturn(Futures.successful(new Object())).when(mockActorContext).executeOperationAsync(
eq(getSystem().actorSelection(actorRef.path())), eqCreateTransaction(memberName, READ_ONLY),
any(Timeout.class));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
propagateReadFailedExceptionCause(transactionProxy.read(TestModel.TEST_PATH));
}
示例11: setUpReadData
import akka.util.Timeout; //導入依賴的package包/類
private void setUpReadData(final String shardName, final NormalizedNode<?, ?> expectedNode) {
ActorSystem actorSystem = getSystem();
ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
.actorSelection(shardActorRef.path().toString());
doReturn(primaryShardInfoReply(getSystem(), shardActorRef)).when(mockActorContext)
.findPrimaryShardAsync(eq(shardName));
ActorRef txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
doReturn(actorSystem.actorSelection(txActorRef.path())).when(mockActorContext)
.actorSelection(txActorRef.path().toString());
doReturn(Futures.successful(createTransactionReply(txActorRef, DataStoreVersions.CURRENT_VERSION)))
.when(mockActorContext).executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
eqCreateTransaction(memberName, TransactionType.READ_ONLY), any(Timeout.class));
doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync(
eq(actorSelection(txActorRef)), eqReadData(YangInstanceIdentifier.EMPTY), any(Timeout.class));
}
示例12: testOnReceiveFindLocalShardWaitForShardInitialized
import akka.util.Timeout; //導入依賴的package包/類
@Test
public void testOnReceiveFindLocalShardWaitForShardInitialized() throws Exception {
LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
new JavaTestKit(getSystem()) {
{
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
// We're passing waitUntilInitialized = true to FindLocalShard
// so the response should be
// delayed until we send ActorInitialized.
Future<Object> future = Patterns.ask(shardManager, new FindLocalShard(Shard.DEFAULT_NAME, true),
new Timeout(5, TimeUnit.SECONDS));
shardManager.tell(new ActorInitialized(), mockShardActor);
Object resp = Await.result(future, duration("5 seconds"));
assertTrue("Expected: LocalShardFound, Actual: " + resp, resp instanceof LocalShardFound);
}
};
LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
}
示例13: ask
import akka.util.Timeout; //導入依賴的package包/類
private <T> ListenableFuture<T> ask(ActorRef actor, Object message, Timeout timeout) {
final SettableFuture<T> returnFuture = SettableFuture.create();
@SuppressWarnings("unchecked")
scala.concurrent.Future<T> askFuture = (scala.concurrent.Future<T>) Patterns.ask(actor, message, timeout);
askFuture.onComplete(new OnComplete<T>() {
@Override
public void onComplete(Throwable failure, T resp) {
if (failure != null) {
returnFuture.setException(failure);
} else {
returnFuture.set(resp);
}
}
}, configDataStore.getActorContext().getClientDispatcher());
return returnFuture;
}
示例14: akkaFuture
import akka.util.Timeout; //導入依賴的package包/類
/**
* 訪問路徑: http://localhost:8080/akka/future
*
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(value = "/akka/future", method = RequestMethod.GET)
public void akkaFuture(HttpServletRequest request, HttpServletResponse response, Model model){
int a = 1;
try {
ActorRef actorRef1 = actorGenerator.createUniqueActor("printerActor", "printerActorName");
PrinterMsg printerMsg = new PrinterMsg(99, "hello world.");
Timeout timeout = new Timeout(Duration.create(10, TimeUnit.SECONDS));
Future<Object> future = Patterns.ask(actorRef1, "hello world", timeout);
Object result = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
int c = 3;
} catch (Exception e) {
logger.error("akka exception:", e);
}
int b = 2;
}
示例15: performsReactively
import akka.util.Timeout; //導入依賴的package包/類
/**
* Performs a reactive mission
*
* @param reactiveMission - the mission to perform
* @param <RESULT> - the type of the missions' result
* @return the actual result of the mission
*/
public <RESULT> Either<RESULT,Failure> performsReactively(ReactiveMission<RESULT> reactiveMission) {
Optional<MissionStrategy> strategyToUse = decideStrategyToUse(reactiveMission);
strategyToUse.ifPresent(strategy -> reactiveMission.withStrategy(strategy));
Either<RESULT,Failure> result;
try {
String strategySet = (String) Await.result(ask(master, asEvent(this, reactiveMission), 1000), timeout);
if (strategySet != "setStrategyCompleted") throw new StrategyException("not properly set");
final FiniteDuration allowedDuration = reactiveMission.strategy().get().timeoutStrategy().first();
Timeout timeoutFromStrategy = Timeout.durationToTimeout(allowedDuration);
RESULT r = (RESULT) Await.result(ask(slave, asEvent(this, reactiveMission), timeoutFromStrategy), allowedDuration);
result = Either.left(r);
} catch (Exception e) {
failure = Failure.failure(e);
result = Either.right(failure);
failed = true;
}
return result;
}