當前位置: 首頁>>代碼示例>>Java>>正文


Java FiniteDuration類代碼示例

本文整理匯總了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()));
    }
 
開發者ID:freedompy,項目名稱:commelina,代碼行數:21,代碼來源:RoomContext.java

示例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);
    }
}
 
開發者ID:pravega,項目名稱:flink-connectors,代碼行數:19,代碼來源:FlinkMiniClusterWithSavepointCommand.java

示例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());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:17,代碼來源:FollowerTest.java

示例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());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:22,代碼來源:RaftActorLeadershipTransferCohort.java

示例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");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:26,代碼來源:RaftActorTest.java

示例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());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:19,代碼來源:AbstractLeader.java

示例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
        );
    }
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:28,代碼來源:Gossiper.java

示例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()
    );
}
 
開發者ID:ironfish,項目名稱:oreilly-reactive-architecture-old,代碼行數:19,代碼來源:Guest.java

示例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()
    );
}
 
開發者ID:ironfish,項目名稱:oreilly-reactive-architecture-old,代碼行數:27,代碼來源:Guest.java

示例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()
        );
    }
 
開發者ID:ironfish,項目名稱:oreilly-reactive-architecture-old,代碼行數:23,代碼來源:Guest.java

示例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);
    }
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:22,代碼來源:DistributedDataStoreTest.java

示例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);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:19,代碼來源:FollowerTest.java

示例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");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:28,代碼來源:RaftActorServerConfigurationSupportTest.java

示例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);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:25,代碼來源:LeaderTest.java

示例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");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:23,代碼來源:RaftActorServerConfigurationSupportTest.java


注:本文中的scala.concurrent.duration.FiniteDuration類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。