當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。