本文整理汇总了Java中scala.concurrent.duration.FiniteDuration类的典型用法代码示例。如果您正苦于以下问题:Java FiniteDuration类的具体用法?Java FiniteDuration怎么用?Java FiniteDuration使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
FiniteDuration类属于scala.concurrent.duration包,在下文中一共展示了FiniteDuration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sendJoinRoomBroadcast
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
private void sendJoinRoomBroadcast() {
FiniteDuration finiteDuration = Duration.create(10, TimeUnit.SECONDS);
// 向客户端广播加入房间的消息
selectFrontend().tell(ActorBroadcast.newBuilder()
.setOpcode(NOTIFY_OPCODE.JOIN_ROOM_VALUE)
.addAllUserIds(players.keySet())
.setMessage(NotifyJoinRoom.newBuilder()
.setRoomId(roomId)
.setOverMicrosecond(System.currentTimeMillis() + finiteDuration.toMillis())
.build().toByteString())
.build(), getSelf());
// ActorSystem system = getContext().getSystem();
//
// // 十秒之后
// players.keySet().forEach(u -> system.scheduler().scheduleOnce(finiteDuration, () -> {
//
// }, system.dispatcher()));
}
示例2: triggerSavepoint
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
public String triggerSavepoint(JobID jobId, URI targetPath) throws Exception {
final String target = new Path(targetPath).toString();
final FiniteDuration timeout = timeout();
final ActorGateway jobManagerGateway = getLeaderGateway(timeout);
Future<Object> savepointPathFuture = jobManagerGateway.ask(
new JobManagerMessages.TriggerSavepoint(jobId, Option.apply(target)), timeout);
Object result = Await.result(savepointPathFuture, timeout);
if (result instanceof JobManagerMessages.TriggerSavepointSuccess) {
return ((JobManagerMessages.TriggerSavepointSuccess) result).savepointPath();
} else if (result instanceof JobManagerMessages.TriggerSavepointFailure) {
throw new SavepointFailedException(((JobManagerMessages.TriggerSavepointFailure) result).cause());
} else {
throw new Exception("Unexpected response: " + result);
}
}
示例3: testFollowerSchedulesElectionIfNonVoting
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
@Test
public void testFollowerSchedulesElectionIfNonVoting() {
MockRaftActorContext context = createActorContext();
context.updatePeerIds(new ServerConfigurationPayload(Arrays.asList(new ServerInfo(context.getId(), false))));
((DefaultConfigParamsImpl)context.getConfigParams()).setHeartBeatInterval(
FiniteDuration.apply(100, TimeUnit.MILLISECONDS));
((DefaultConfigParamsImpl)context.getConfigParams()).setElectionTimeoutFactor(1);
follower = new Follower(context, "leader", (short)1);
ElectionTimeout electionTimeout = MessageCollectorActor.expectFirstMatching(followerActor,
ElectionTimeout.class);
RaftActorBehavior newBehavior = follower.handleMessage(ActorRef.noSender(), electionTimeout);
assertSame("handleMessage result", follower, newBehavior);
assertNull("Expected null leaderId", follower.getLeaderId());
}
示例4: transferComplete
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
/**
* This method is invoked when leadership transfer was carried out and complete.
*/
public void transferComplete() {
LOG.debug("{}: leader transfer complete - waiting for new leader", raftActor.persistenceId());
// We'll give it a little time for the new leader to be elected to give the derived class a
// chance to possibly complete work that was suspended while we were transferring. The
// RequestVote message from the new leader candidate should cause us to step down as leader
// and convert to follower due to higher term. We should then get an AppendEntries heart
// beat with the new leader id.
// Add a timer in case we don't get a leader change. Note: the Runnable is sent as a message to the raftActor
// which executes it safely run on the actor's thread dispatcher.
FiniteDuration timeout = FiniteDuration.create(newLeaderTimeoutInMillis, TimeUnit.MILLISECONDS);
newLeaderTimer = raftActor.getContext().system().scheduler().scheduleOnce(timeout, raftActor.self(),
(Runnable) () -> {
LOG.debug("{}: leader not elected in time", raftActor.persistenceId());
finish(true);
}, raftActor.getContext().system().dispatcher(), raftActor.self());
}
示例5: testNonVotingOnRecovery
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
@Test
public void testNonVotingOnRecovery() throws Exception {
TEST_LOG.info("testNonVotingOnRecovery starting");
DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
config.setElectionTimeoutFactor(1);
config.setHeartBeatInterval(FiniteDuration.create(1, TimeUnit.MILLISECONDS));
String persistenceId = factory.generateActorId("test-actor-");
InMemoryJournal.addEntry(persistenceId, 1, new SimpleReplicatedLogEntry(0, 1,
new ServerConfigurationPayload(Arrays.asList(new ServerInfo(persistenceId, false)))));
TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId)
.config(config).props().withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
mockRaftActor.waitForInitializeBehaviorComplete();
// Sleep a bit and verify it didn't get an election timeout and schedule an election.
Uninterruptibles.sleepUninterruptibly(400, TimeUnit.MILLISECONDS);
assertEquals("getRaftState", RaftState.Follower, mockRaftActor.getRaftState());
TEST_LOG.info("testNonVotingOnRecovery ending");
}
示例6: scheduleHeartBeat
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
private void scheduleHeartBeat(final FiniteDuration interval) {
if (followerToLog.isEmpty()) {
// Optimization - do not bother scheduling a heartbeat as there are
// no followers
return;
}
stopHeartBeat();
// Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
// message is sent to itself.
// Scheduling the heartbeat only once here because heartbeats do not
// need to be sent if there are other messages being sent to the remote
// actor.
heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
interval, context.getActor(), SendHeartBeat.INSTANCE,
context.getActorSystem().dispatcher(), context.getActor());
}
示例7: preStart
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
@Override
public void preStart() {
ActorRefProvider provider = getContext().provider();
selfAddress = provider.getDefaultAddress();
bucketStore = new BucketStoreAccess(getContext(), config.getAskDuration());
if (provider instanceof ClusterActorRefProvider) {
cluster = Cluster.get(getContext().system());
cluster.subscribe(getSelf(),
ClusterEvent.initialStateAsEvents(),
ClusterEvent.MemberEvent.class,
ClusterEvent.ReachableMember.class,
ClusterEvent.UnreachableMember.class);
}
if (autoStartGossipTicks) {
gossipTask = getContext().system().scheduler().schedule(
new FiniteDuration(1, TimeUnit.SECONDS), //initial delay
config.getGossipTickInterval(), //interval
getSelf(), //target
GOSSIP_TICK, //message
getContext().dispatcher(), //execution context
getSelf() //sender
);
}
}
示例8: Guest
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
public Guest(ActorRef waiter, Coffee favoriteCoffee, FiniteDuration finishCoffeeDuration) {
this.waiter = waiter;
this.favoriteCoffee = favoriteCoffee;
this.finishCoffeeDuration = finishCoffeeDuration;
orderFavoriteCoffee();
receive(ReceiveBuilder.
match(Waiter.CoffeeServed.class, coffeeServed -> {
coffeeCount++;
log().info("Enjoying my {} yummy {}!", coffeeCount, coffeeServed.coffee);
scheduleCoffeeFinished();
}).
match(CoffeeFinished.class, coffeeFinished ->
orderFavoriteCoffee()
).
matchAny(this::unhandled).build()
);
}
示例9: Guest
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
public Guest(ActorRef waiter, Coffee favoriteCoffee, FiniteDuration finishCoffeeDuration, int caffeineLimit) {
this.waiter = waiter;
this.favoriteCoffee = favoriteCoffee;
this.finishCoffeeDuration = finishCoffeeDuration;
this.caffeineLimit = caffeineLimit;
orderFavoriteCoffee();
receive(ReceiveBuilder.
match(Waiter.CoffeeServed.class, coffeeServed -> coffeeServed.coffee.equals(favoriteCoffee), coffeeServed -> {
coffeeCount++;
log().info("Enjoying my {} yummy {}!", coffeeCount, coffeeServed.coffee);
scheduleCoffeeFinished();
}).
match(Waiter.CoffeeServed.class, coffeeServed -> {
log().info("Expected a {}, but got a {}!", favoriteCoffee, coffeeServed.coffee);
waiter.tell(new Waiter.Complaint(favoriteCoffee), self());
}).
match(CoffeeFinished.class, coffeeFinished -> coffeeCount > this.caffeineLimit, coffeeFinished -> {
throw new CaffeineException();
}).
match(CoffeeFinished.class, coffeeFinished ->
orderFavoriteCoffee()
).
matchAny(this::unhandled).build()
);
}
示例10: Guest
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
public Guest(ActorRef waiter, Coffee favoriteCoffee, FiniteDuration finishCoffeeDuration) {
this.waiter = waiter;
this.favoriteCoffee = favoriteCoffee;
this.finishCoffeeDuration = finishCoffeeDuration;
// this.caffeineLimit = caffeineLimit;
orderFavoriteCoffee();
receive(ReceiveBuilder.
match(Waiter.CoffeeServed.class, coffeeServed -> {
coffeeCount++;
log().info("Enjoying my {} yummy {}!", coffeeCount, coffeeServed.coffee);
scheduleCoffeeFinished();
}).
// match(CoffeeFinished.class, coffeeFinished -> coffeeCount > this.caffeineLimit, coffeeFinished -> {
// throw new CaffeineException();
// }).
match(CoffeeFinished.class, coffeeFinished ->
orderFavoriteCoffee()
).
matchAny(this::unhandled).build()
);
}
示例11: testWaitTillReadyCountDown
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
@Test
public void testWaitTillReadyCountDown() {
try (DistributedDataStore distributedDataStore = new DistributedDataStore(actorContext, UNKNOWN_ID)) {
doReturn(datastoreContext).when(actorContext).getDatastoreContext();
doReturn(shardElectionTimeout).when(datastoreContext).getShardLeaderElectionTimeout();
doReturn(FiniteDuration.apply(5000, TimeUnit.MILLISECONDS)).when(shardElectionTimeout).duration();
Executors.newSingleThreadExecutor().submit(() -> {
Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
distributedDataStore.getWaitTillReadyCountDownLatch().countDown();
});
long start = System.currentTimeMillis();
distributedDataStore.waitTillReady();
long end = System.currentTimeMillis();
assertTrue("Expected to be released in 500 millis", end - start < 5000);
}
}
示例12: testFollowerSchedulesElectionIfAutomaticElectionsAreDisabled
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
@Test
public void testFollowerSchedulesElectionIfAutomaticElectionsAreDisabled() {
MockRaftActorContext context = createActorContext();
context.setConfigParams(new DefaultConfigParamsImpl() {
@Override
public FiniteDuration getElectionTimeOutInterval() {
return FiniteDuration.apply(100, TimeUnit.MILLISECONDS);
}
});
context.setRaftPolicy(createRaftPolicy(false, false));
follower = createBehavior(context);
TimeoutNow timeoutNow = MessageCollectorActor.expectFirstMatching(followerActor, TimeoutNow.class);
RaftActorBehavior newBehavior = follower.handleMessage(ActorRef.noSender(), timeoutNow);
assertSame("handleMessage result", follower, newBehavior);
}
示例13: testAddServerForwardedToLeader
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
@Test
public void testAddServerForwardedToLeader() {
LOG.info("testAddServerForwardedToLeader starting");
setupNewFollower();
DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
ActorRef leaderActor = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId(LEADER_ID));
TestActorRef<MockRaftActor> followerRaftActor = actorFactory.createTestActor(
MockRaftActor.builder().id(FOLLOWER_ID).peerAddresses(ImmutableMap.of(LEADER_ID,
leaderActor.path().toString())).config(configParams).persistent(Optional.of(false))
.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(FOLLOWER_ID));
followerRaftActor.underlyingActor().waitForInitializeBehaviorComplete();
followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, Collections.<ReplicatedLogEntry>emptyList(),
-1, -1, (short)0), leaderActor);
followerRaftActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true),
testKit.getRef());
expectFirstMatching(leaderActor, AddServer.class);
LOG.info("testAddServerForwardedToLeader ending");
}
示例14: testHandleAppendEntriesReplyWithNewerTermWhenElectionsAreDisabled
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
@Test
public void testHandleAppendEntriesReplyWithNewerTermWhenElectionsAreDisabled() {
logStart("testHandleAppendEntriesReplyWithNewerTermWhenElectionsAreDisabled");
MockRaftActorContext leaderActorContext = createActorContext();
((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setHeartBeatInterval(
new FiniteDuration(10000, TimeUnit.SECONDS));
leaderActorContext.setReplicatedLog(
new MockRaftActorContext.MockReplicatedLogBuilder().createEntries(0, 2, 2).build());
leaderActorContext.setRaftPolicy(createRaftPolicy(false, false));
leader = new Leader(leaderActorContext);
leaderActor.underlyingActor().setBehavior(leader);
leaderActor.tell(new AppendEntriesReply("foo", 20, false, 1000, 10, (short) 1), ActorRef.noSender());
AppendEntriesReply appendEntriesReply = MessageCollectorActor.expectFirstMatching(leaderActor,
AppendEntriesReply.class);
assertEquals(false, appendEntriesReply.isSuccess());
assertEquals(RaftState.Leader, leaderActor.underlyingActor().getFirstBehaviorChange().state());
MessageCollectorActor.clearMessages(leaderActor);
}
示例15: testAddServerWithNoLeader
import scala.concurrent.duration.FiniteDuration; //导入依赖的package包/类
@Test
public void testAddServerWithNoLeader() {
LOG.info("testAddServerWithNoLeader starting");
setupNewFollower();
DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
TestActorRef<MockRaftActor> noLeaderActor = actorFactory.createTestActor(
MockRaftActor.builder().id(LEADER_ID).peerAddresses(ImmutableMap.of(FOLLOWER_ID,
followerActor.path().toString())).config(configParams).persistent(Optional.of(false))
.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
noLeaderActor.underlyingActor().waitForInitializeBehaviorComplete();
noLeaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true),
testKit.getRef());
AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
assertEquals("getStatus", ServerChangeStatus.NO_LEADER, addServerReply.getStatus());
LOG.info("testAddServerWithNoLeader ending");
}