当前位置: 首页>>代码示例>>Java>>正文


Java Uninterruptibles类代码示例

本文整理汇总了Java中com.google.common.util.concurrent.Uninterruptibles的典型用法代码示例。如果您正苦于以下问题:Java Uninterruptibles类的具体用法?Java Uninterruptibles怎么用?Java Uninterruptibles使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Uninterruptibles类属于com.google.common.util.concurrent包,在下文中一共展示了Uninterruptibles类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: verifyActorReady

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的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);
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:26,代码来源:TestActorFactory.java

示例2: verifyShardState

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
public static void verifyShardState(final AbstractDataStore datastore, final String shardName,
        final Consumer<OnDemandShardState> verifier) throws Exception {
    ActorContext actorContext = datastore.getActorContext();

    Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
    ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));

    AssertionError lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
        OnDemandShardState shardState = (OnDemandShardState)actorContext
                .executeOperation(shardActor, GetOnDemandRaftState.INSTANCE);

        try {
            verifier.accept(shardState);
            return;
        } catch (AssertionError e) {
            lastError = e;
            Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        }
    }

    throw lastError;
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:25,代码来源:IntegrationTestKit.java

示例3: testWaitTillReadyCountDown

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的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

示例4: 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

示例5: main

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
public static void main(String[] args) {
  Flux<Integer> flux = Flux.<Integer>push(e -> {
    // imagine reading from DB row by row or from file line by line
    for (int fi = 0; fi < 30; fi++) {
      Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
      e.next(fi);
    }
  })
      .log()
      .subscribeOn(emitter)
      .log();

  flux.flatMap(
      // could be some other IO like reading from a second database
      i -> Mono.fromSupplier(() -> i + " - " + i * 2)
          .log()
          .subscribeOn(transformer)
          .log()
          .publishOn(consumer))
      .log()
      .collectList()
      .log().block();
}
 
开发者ID:akiraly,项目名称:playing-reactor,代码行数:24,代码来源:Flux2.java

示例6: write

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
@Override
public void write(Message message) {
    Uninterruptibles.awaitUninterruptibly(transportInitialized);

    LOG.debug("Sending message: {}", message);

    try {
        final GelfMessageBuilder messageBuilder = new GelfMessageBuilder(message.getMessage(), message.getSource())
                .timestamp(message.getTimestamp().getMillis() / 1000.0)
                .additionalFields(message.getFields().asMap());

        if (message.getLevel() != null) {
            messageBuilder.level(GelfMessageLevel.valueOf(message.getLevel().toString()));
        } else {
            messageBuilder.level(null);
        }

        transport.send(messageBuilder.build());
    } catch (InterruptedException e) {
        LOG.error("Failed to send message", e);
    }
}
 
开发者ID:DevOpsStudio,项目名称:Re-Collector,代码行数:23,代码来源:GelfOutput.java

示例7: close

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
/**
 * Close the DomainSocketWatcher and wait for its thread to terminate.
 *
 * If there is more than one close, all but the first will be ignored.
 */
@Override
public void close() throws IOException {
  lock.lock();
  try {
    if (closed) return;
    if (LOG.isDebugEnabled()) {
      LOG.debug(this + ": closing");
    }
    closed = true;
  } finally {
    lock.unlock();
  }
  // Close notificationSockets[0], so that notificationSockets[1] gets an EOF
  // event.  This will wake up the thread immediately if it is blocked inside
  // the select() system call.
  notificationSockets[0].close();
  // Wait for the select thread to terminate.
  Uninterruptibles.joinUninterruptibly(watcherThread);
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:25,代码来源:DomainSocketWatcher.java

示例8: refresh

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
/**
 * Refreshes the value associated with {@code key}, unless another thread is already doing so.
 * Returns the newly refreshed value associated with {@code key} if it was refreshed inline, or
 * {@code null} if another thread is performing the refresh or if an error occurs during
 * refresh.
 */
@Nullable
V refresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) {
  final LoadingValueReference<K, V> loadingValueReference =
      insertLoadingValueReference(key, hash, checkTime);
  if (loadingValueReference == null) {
    return null;
  }

  ListenableFuture<V> result = loadAsync(key, hash, loadingValueReference, loader);
  if (result.isDone()) {
    try {
      return Uninterruptibles.getUninterruptibly(result);
    } catch (Throwable t) {
      // don't let refresh exceptions propagate; error was already logged
    }
  }
  return null;
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:25,代码来源:LocalCache.java

示例9: 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

示例10: 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

示例11: verifyEmptyBucket

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
private void verifyEmptyBucket(final JavaTestKit testKit, final ActorRef registry, final Address address)
        throws AssertionError {
    Map<Address, Bucket<RoutingTable>> buckets;
    int numTries = 0;
    while (true) {
        buckets = retrieveBuckets(registry1, testKit, address);

        try {
            verifyBucket(buckets.get(address), Collections.emptyList());
            break;
        } catch (AssertionError e) {
            if (++numTries >= 50) {
                throw e;
            }
        }

        Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:20,代码来源:RpcRegistryTest.java

示例12: testAssembledMessageStateExpiration

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
@Test
public void testAssembledMessageStateExpiration() throws IOException {
    final int expiryDuration = 200;
    try (MessageAssembler assembler = newMessageAssemblerBuilder("testAssembledMessageStateExpiration")
            .expireStateAfterInactivity(expiryDuration, TimeUnit.MILLISECONDS).build()) {
        final MessageSliceIdentifier identifier = new MessageSliceIdentifier(IDENTIFIER, 1);
        final BytesMessage message = new BytesMessage(new byte[]{1, 2, 3});

        final MessageSlice messageSlice = new MessageSlice(identifier, SerializationUtils.serialize(message), 1, 2,
                SlicedMessageState.INITIAL_SLICE_HASH_CODE, testProbe.ref());
        assembler.handleMessage(messageSlice, testProbe.ref());

        final MessageSliceReply reply = testProbe.expectMsgClass(MessageSliceReply.class);
        assertSuccessfulMessageSliceReply(reply, IDENTIFIER, 1);

        assertTrue("MessageAssembler should have remove state for " + identifier, assembler.hasState(identifier));
        Uninterruptibles.sleepUninterruptibly(expiryDuration + 50, TimeUnit.MILLISECONDS);
        assertFalse("MessageAssembler did not remove state for " + identifier, assembler.hasState(identifier));

        verify(mockFiledBackedStream).cleanup();
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:23,代码来源:MessageAssemblerTest.java

示例13: AsyncCopier

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
@VisibleForTesting
AsyncCopier(
    InputStream source,
    OutputStream sink,
    Supplier<Level> ioExceptionLogLevel,
    CopyStrategy copyStrategy,
    ExecutorService executorService) {
  this.source = source;
  this.sink = sink;
  this.ioExceptionLogLevel = ioExceptionLogLevel;
  this.copyStrategy = copyStrategy;

  // Submit the copy task and wait uninterruptibly, but very briefly, for it to actually start.
  copyFuture = executorService.submit(new Runnable() {
    @Override public void run() {
      copy();
    }
  });
  Uninterruptibles.awaitUninterruptibly(copyStarted);
}
 
开发者ID:google,项目名称:ios-device-control,代码行数:21,代码来源:AsyncCopier.java

示例14: removeVolumeScanner

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
/**
 * Stops and removes a volume scanner.<p/>
 *
 * This function will block until the volume scanner has stopped.
 *
 * @param volume           The volume to remove.
 */
public synchronized void removeVolumeScanner(FsVolumeSpi volume) {
  if (!isEnabled()) {
    LOG.debug("Not removing volume scanner for {}, because the block " +
        "scanner is disabled.", volume.getStorageID());
    return;
  }
  VolumeScanner scanner = scanners.get(volume.getStorageID());
  if (scanner == null) {
    LOG.warn("No scanner found to remove for volumeId {}",
        volume.getStorageID());
    return;
  }
  LOG.info("Removing scanner for volume {} (StorageID {})",
      volume.getBasePath(), volume.getStorageID());
  scanner.shutdown();
  scanners.remove(volume.getStorageID());
  Uninterruptibles.joinUninterruptibly(scanner, 5, TimeUnit.MINUTES);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:26,代码来源:BlockScanner.java

示例15: verifyShardStats

import com.google.common.util.concurrent.Uninterruptibles; //导入依赖的package包/类
public static void verifyShardStats(final AbstractDataStore datastore, final String shardName,
        final ShardStatsVerifier verifier) throws Exception {
    ActorContext actorContext = datastore.getActorContext();

    Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
    ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));

    AssertionError lastError = null;
    Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
        ShardStats shardStats = (ShardStats)actorContext
                .executeOperation(shardActor, Shard.GET_SHARD_MBEAN_MESSAGE);

        try {
            verifier.verify(shardStats);
            return;
        } catch (AssertionError e) {
            lastError = e;
            Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
        }
    }

    throw lastError;
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:25,代码来源:IntegrationTestKit.java


注:本文中的com.google.common.util.concurrent.Uninterruptibles类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。