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


Java Uninterruptibles.sleepUninterruptibly方法代碼示例

本文整理匯總了Java中com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly方法的典型用法代碼示例。如果您正苦於以下問題:Java Uninterruptibles.sleepUninterruptibly方法的具體用法?Java Uninterruptibles.sleepUninterruptibly怎麽用?Java Uninterruptibles.sleepUninterruptibly使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.common.util.concurrent.Uninterruptibles的用法示例。


在下文中一共展示了Uninterruptibles.sleepUninterruptibly方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
public static void main(String[] args) {
  Flux<LocalDateTime> flux = Flux.<LocalDateTime>create(e -> {
    Schedulers.newSingle("brc", true)
        .schedulePeriodically(
            () -> {
              LOGGER.info("calculating...");
              e.next(LocalDateTime.now(ZoneOffset.UTC));
            },
            0, 100, TimeUnit.MILLISECONDS);
  }, OverflowStrategy.LATEST).cache(1);

  flux.blockFirst();

  while (true) {
    LOGGER.info("{}", flux.blockFirst(Duration.ofMillis(0)));
    Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
  }
}
 
開發者ID:akiraly,項目名稱:playing-reactor,代碼行數:19,代碼來源:BackgroundRefreshingCache.java

示例2: call

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
@Override
public T call() {
    T result;
    while (true) {
        try {
            result = callable.call();
            break;
        } catch (Throwable e) {
            if (retryOn.stream().noneMatch(c -> getAllCauses(e).anyMatch(c::isInstance))) {
                throw Throwables.propagate(e);
            }
            log.warn(errorMessage + ", retry in " + delaySec + " sec: " + e.toString());
            Uninterruptibles.sleepUninterruptibly(delaySec, TimeUnit.SECONDS);
        }
    }
    return result;
}
 
開發者ID:papyrusglobal,項目名稱:state-channels,代碼行數:18,代碼來源:Retriable.java

示例3: createTestActor

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
/**
 * Create a test actor with the passed in name.
 *
 * @param props the actor Props
 * @param actorId name of actor
 * @param <T> the actor type
 * @return the ActorRef
 */
@SuppressWarnings("unchecked")
public <T extends Actor> TestActorRef<T> createTestActor(Props props, String actorId) {
    InvalidActorNameException lastError = null;
    for (int i = 0; i < 10; i++) {
        try {
            TestActorRef<T> actorRef = TestActorRef.create(system, props, actorId);
            return (TestActorRef<T>) addActor(actorRef, true);
        } catch (InvalidActorNameException e) {
            lastError = e;
            Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
        }
    }

    throw lastError;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:24,代碼來源:TestActorFactory.java

示例4: waitForMembersUp

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
public void waitForMembersUp(final String... otherMembers) {
    Set<String> otherMembersSet = Sets.newHashSet(otherMembers);
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
        CurrentClusterState state = Cluster.get(getSystem()).state();
        for (Member m: state.getMembers()) {
            if (m.status() == MemberStatus.up() && otherMembersSet.remove(m.getRoles().iterator().next())
                    && otherMembersSet.isEmpty()) {
                return;
            }
        }

        Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
    }

    fail("Member(s) " + otherMembersSet + " are not Up");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:18,代碼來源:IntegrationTestKit.java

示例5: verifyRaftState

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的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;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:21,代碼來源:AbstractEntityOwnershipTest.java

示例6: testRestoreFromSnapshotWithRecoveredData

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
@Test
public void testRestoreFromSnapshotWithRecoveredData() throws Exception {
    TEST_LOG.info("testRestoreFromSnapshotWithRecoveredData starting");

    String persistenceId = factory.generateActorId("test-actor-");
    DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
    config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());

    List<MockPayload> state = Arrays.asList(new MockRaftActorContext.MockPayload("A"));
    Snapshot snapshot = Snapshot.create(ByteState.of(fromObject(state).toByteArray()),
            Arrays.<ReplicatedLogEntry>asList(), 5, 2, 5, 2, 2, "member-1", null);

    InMemoryJournal.addEntry(persistenceId, 1, new SimpleReplicatedLogEntry(0, 1,
            new MockRaftActorContext.MockPayload("B")));

    TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId)
            .config(config).restoreFromSnapshot(snapshot).props()
                .withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
    MockRaftActor mockRaftActor = raftActorRef.underlyingActor();

    mockRaftActor.waitForRecoveryComplete();

    Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
    verify(mockRaftActor.snapshotCohortDelegate, never()).applySnapshot(any(Snapshot.State.class));

    RaftActorContext context = mockRaftActor.getRaftActorContext();
    assertEquals("Journal log size", 1, context.getReplicatedLog().size());
    assertEquals("Last index", 0, context.getReplicatedLog().lastIndex());
    assertEquals("Last applied", -1, context.getLastApplied());
    assertEquals("Commit index", -1, context.getCommitIndex());
    assertEquals("Current term", 0, context.getTermInformation().getCurrentTerm());
    assertEquals("Voted for", null, context.getTermInformation().getVotedFor());

    TEST_LOG.info("testRestoreFromSnapshotWithRecoveredData ending");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:36,代碼來源:RaftActorTest.java

示例7: assertNoneMatching

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
@SuppressWarnings("checkstyle:IllegalCatch")
public static <T> void assertNoneMatching(final ActorRef actor, final Class<T> clazz, final long timeout) {
    Exception lastEx = null;
    int count = (int) (timeout / 50);
    for (int i = 0; i < count; i++) {
        try {
            T message = getFirstMatching(actor, clazz);
            if (message != null) {
                Assert.fail("Unexpected message received" +  message.toString());
                return;
            }

            lastEx = null;
        } catch (Exception e) {
            lastEx = e;
        }

        Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
    }

    if (lastEx != null) {
        Throwables.throwIfUnchecked(lastEx);
        throw new RuntimeException(lastEx);
    }

    return;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:28,代碼來源:MessageCollectorActor.java

示例8: testSendingReplicateImmediatelyAfterHeartbeatDoesReplicate

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
@Test
public void testSendingReplicateImmediatelyAfterHeartbeatDoesReplicate() throws Exception {
    logStart("testSendingReplicateImmediatelyAfterHeartbeatDoesReplicate");

    MockRaftActorContext actorContext = createActorContextWithFollower();
    actorContext.setConfigParams(new DefaultConfigParamsImpl() {
        @Override
        public FiniteDuration getHeartBeatInterval() {
            return FiniteDuration.apply(100, TimeUnit.MILLISECONDS);
        }
    });

    long term = 1;
    actorContext.getTermInformation().update(term, "");

    leader = new Leader(actorContext);

    // Leader will send an immediate heartbeat - ignore it.
    MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);

    // The follower would normally reply - simulate that explicitly here.
    long lastIndex = actorContext.getReplicatedLog().lastIndex();
    leader.handleMessage(followerActor, new AppendEntriesReply(
            FOLLOWER_ID, term, true, lastIndex, term, (short)0));
    assertEquals("isFollowerActive", true, leader.getFollower(FOLLOWER_ID).isFollowerActive());

    followerActor.underlyingActor().clear();

    Uninterruptibles.sleepUninterruptibly(150, TimeUnit.MILLISECONDS);
    leader.handleMessage(leaderActor, SendHeartBeat.INSTANCE);
    sendReplicate(actorContext, lastIndex + 1);

    List<AppendEntries> allMessages = MessageCollectorActor.getAllMatching(followerActor, AppendEntries.class);
    assertEquals("The number of append entries collected should be 2", 2, allMessages.size());

    assertEquals(0, allMessages.get(0).getEntries().size());
    assertEquals(1, allMessages.get(1).getEntries().size());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:39,代碼來源:LeaderTest.java

示例9: waitUntilLeader

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
public void waitUntilLeader() {
    for (int i = 0; i < 10; i++) {
        if (isLeader()) {
            break;
        }
        Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
    }
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:9,代碼來源:MockRaftActor.java

示例10: testHandleElectionTimeoutWhenNoLeaderMessageReceived

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
@Test
public void testHandleElectionTimeoutWhenNoLeaderMessageReceived() {
    logStart("testHandleElectionTimeoutWhenNoLeaderMessageReceived");

    MockRaftActorContext context = createActorContext();
    follower = new Follower(context);

    Uninterruptibles.sleepUninterruptibly(context.getConfigParams().getElectionTimeOutInterval().toMillis(),
            TimeUnit.MILLISECONDS);
    RaftActorBehavior raftBehavior = follower.handleMessage(leaderActor, ElectionTimeout.INSTANCE);

    assertTrue(raftBehavior instanceof Candidate);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:14,代碼來源:FollowerTest.java

示例11: testAddRoutesConcurrency

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
@Test
public void testAddRoutesConcurrency() throws Exception {
    final JavaTestKit testKit = new JavaTestKit(node1);

    final int nRoutes = 500;
    final Collection<DOMRpcIdentifier> added = new ArrayList<>(nRoutes);
    for (int i = 0; i < nRoutes; i++) {
        final DOMRpcIdentifier routeId = DOMRpcIdentifier.create(SchemaPath.create(true,
                new QName(new URI("/mockrpc"), "type" + i)));
        added.add(routeId);

        //Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        registry1.tell(new AddOrUpdateRoutes(Arrays.asList(routeId)),
                ActorRef.noSender());
    }

    FiniteDuration duration = Duration.create(3, TimeUnit.SECONDS);
    int numTries = 0;
    while (true) {
        registry1.tell(GET_ALL_BUCKETS, testKit.getRef());
        @SuppressWarnings("unchecked")
        Map<Address, Bucket<RoutingTable>> buckets = testKit.expectMsgClass(duration, Map.class);

        Bucket<RoutingTable> localBucket = buckets.values().iterator().next();
        RoutingTable table = localBucket.getData();
        if (table != null && table.size() == nRoutes) {
            for (DOMRpcIdentifier r : added) {
                Assert.assertTrue("RoutingTable contains " + r, table.contains(r));
            }

            break;
        }

        if (++numTries >= 50) {
            Assert.fail("Expected # routes: " + nRoutes + ", Actual: " + table.size());
        }

        Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
    }
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:41,代碼來源:RpcRegistryTest.java

示例12: testApplyState

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
@Test
public void testApplyState() throws Exception {
    final TestActorRef<Shard> shard = actorFactory.createTestActor(
            newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");

    ShardTestKit.waitUntilLeader(shard);

    final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
    store.setSchemaContext(SCHEMA_CONTEXT);

    final DataTreeModification writeMod = store.takeSnapshot().newModification();
    final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
    writeMod.write(TestModel.TEST_PATH, node);
    writeMod.ready();

    final TransactionIdentifier tx = nextTransactionId();
    shard.underlyingActor().applyState(null, null, payloadForModification(store, writeMod, tx));

    final Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
        Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);

        final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
        if (actual != null) {
            assertEquals("Applied state", node, actual);
            return;
        }
    }

    fail("State was not applied");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:32,代碼來源:ShardTest.java

示例13: expectFirstMatching

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
@SuppressWarnings("checkstyle:IllegalCatch")
public static <T> T expectFirstMatching(final ActorRef actor, final Class<T> clazz, final Predicate<T> matcher) {
    int timeout = 5000;
    Exception lastEx = null;
    T lastMessage = null;
    for (int i = 0; i < timeout / 50; i++) {
        try {
            List<T> messages = getAllMatching(actor, clazz);
            for (T msg : messages) {
                if (matcher.apply(msg)) {
                    return msg;
                }

                lastMessage = msg;
            }

            lastEx = null;
        } catch (Exception e) {
            lastEx = e;
        }

        Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
    }

    throw new AssertionError(String.format("Expected specific message of type %s. Last message received was: %s",
            clazz, lastMessage), lastEx);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:28,代碼來源:MessageCollectorActor.java

示例14: testTransferLeadershipWithFollowerInitiallyOutOfSync

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
@Test
public void testTransferLeadershipWithFollowerInitiallyOutOfSync() {
    logStart("testTransferLeadershipWithFollowerInitiallyOutOfSync");

    MockRaftActorContext leaderActorContext = createActorContextWithFollower();
    ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setHeartBeatInterval(
            new FiniteDuration(200, TimeUnit.MILLISECONDS));

    leader = new Leader(leaderActorContext);
    leaderActorContext.setCurrentBehavior(leader);

    // Initial heartbeat
    MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);
    MessageCollectorActor.clearMessages(followerActor);

    RaftActorLeadershipTransferCohort mockTransferCohort = mock(RaftActorLeadershipTransferCohort.class);
    doReturn(Optional.absent()).when(mockTransferCohort).getRequestedFollowerId();
    leader.transferLeadership(mockTransferCohort);

    verify(mockTransferCohort, never()).transferComplete();

    // Sync up the follower.
    MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);
    leader.handleMessage(leaderActor, new AppendEntriesReply(FOLLOWER_ID, 1, true, -1, -1, (short)0));
    MessageCollectorActor.clearMessages(followerActor);

    Uninterruptibles.sleepUninterruptibly(leaderActorContext.getConfigParams()
            .getHeartBeatInterval().toMillis() + 1, TimeUnit.MILLISECONDS);
    leader.handleMessage(leaderActor, SendHeartBeat.INSTANCE);
    MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);
    leader.handleMessage(leaderActor, new AppendEntriesReply(FOLLOWER_ID, 1, true, 1, 1, (short)0));

    // Leader should force an election timeout
    MessageCollectorActor.expectFirstMatching(followerActor, TimeoutNow.class);

    verify(mockTransferCohort).transferComplete();
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:38,代碼來源:LeaderTest.java

示例15: getResponse

import com.google.common.util.concurrent.Uninterruptibles; //導入方法依賴的package包/類
private MockResponse getResponse(RecordedRequest request) {
	String path = request.getPath();
	if (!request.getPath().startsWith("/")) path = "/" + path;

	callTimes.add(System.currentTimeMillis());

	HttpUrl url = HttpUrl.parse("http://localhost" + path);

	String apiKey = url.queryParameter("api_key");
	if (!Objects.equals(Constants.API_KEY, apiKey)) {
		return new MockResponse().setBody("\n" +
			"<html>\n" +
			"<head><title>403 Forbidden</title></head>\n" +
			"<body bgcolor=\"white\">\n" +
			"<center><h1>403 Forbidden</h1></center>\n" +
			"<hr><center>openresty/1.9.3.2</center>\n" +
			"</body>\n" +
			"</html>\n" +
			"<!-- a padding to disable MSIE and Chrome friendly error page -->\n" +
			"<!-- a padding to disable MSIE and Chrome friendly error page -->\n" +
			"<!-- a padding to disable MSIE and Chrome friendly error page -->\n" +
			"<!-- a padding to disable MSIE and Chrome friendly error page -->\n" +
			"<!-- a padding to disable MSIE and Chrome friendly error page -->\n" +
			"<!-- a padding to disable MSIE and Chrome friendly error page -->\n")
			.setResponseCode(403);
	}

	path = getPath(request, url);
	InputStream jsonStream = getClass().getClassLoader().getResourceAsStream(path);

	if (jsonStream == null) {
		return null;
	}

	Uninterruptibles.sleepUninterruptibly(delay, TimeUnit.MILLISECONDS);

	return Constants.GSON.fromJson(new InputStreamReader(jsonStream), MockResponse.class);
}
 
開發者ID:LogicalOverflow,項目名稱:java-champion-gg-wrapper,代碼行數:39,代碼來源:MockDispatcher.java


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