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