Java com.google.common.util.concurrent.Uninterruptibles 代码实例

・16 分钟阅读

以下是展示如何使用com.google.common.util.concurrent.Uninterruptibles的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * Pipe the log of the delegated execution through to our log.
 *
 * Modeled after Jenkins' Run's writeWholeLogTo, which is not giving us
 * annotations back.  From the javadoc:
 * "If someone is still writing to the log, this method will not
 * return until the whole log file gets written out."
 */
private void writeWholeLogTo(AbstractBuild build, OutputStream out)
    throws IOException {
  long pos = 0;
  while (!build.getLogFile().exists()
      || build.getLogFile().isDirectory()) {
    Uninterruptibles.sleepUninterruptibly(1, SECONDS);
  }
  do {
    LargeText logText = new LargeText(build.getLogFile(),
        build.getCharset(), !build.isLogUpdated());
    pos = logText.writeLogTo(pos, out);
    if (logText.isComplete()) {
      break;
    }
    Uninterruptibles.sleepUninterruptibly(1, SECONDS);
  } while (true);
}
 

实例 2


/**
 * This method will begin removing an existing endpoint from the cluster by spoofing its state
 * This should never be called unless this coordinator has had 'removenode' invoked
 *
 * @param endpoint    - the endpoint being removed
 * @param hostId      - the ID of the host being removed
 * @param localHostId - my own host ID for replication coordination
 */
public void advertiseRemoving(InetAddress endpoint, UUID hostId, UUID localHostId)
{
    EndpointState epState = endpointStateMap.get(endpoint);
    // remember this node's generation
    int generation = epState.getHeartBeatState().getGeneration();
    logger.info("Removing host: {}", hostId);
    logger.info("Sleeping for " + StorageService.RING_DELAY + "ms to ensure " + endpoint + " does not change");
    Uninterruptibles.sleepUninterruptibly(StorageService.RING_DELAY, TimeUnit.MILLISECONDS);
    // make sure it did not change
    epState = endpointStateMap.get(endpoint);
    if (epState.getHeartBeatState().getGeneration() != generation)
        throw new RuntimeException("Endpoint " + endpoint + " generation changed while trying to remove it");
    // update the other node's generation to mimic it as if it had changed it itself
    logger.info("Advertising removal for " + endpoint);
    epState.updateTimestamp(); // make sure we don't evict it too soon
    epState.getHeartBeatState().forceNewerGenerationUnsafe();
    epState.addApplicationState(ApplicationState.STATUS, StorageService.instance.valueFactory.removingNonlocal(hostId));
    epState.addApplicationState(ApplicationState.REMOVAL_COORDINATOR, StorageService.instance.valueFactory.removalCoordinator(localHostId));
    endpointStateMap.put(endpoint, epState);
}
 

实例 3


/**
 * Handles switching the endpoint's state from REMOVING_TOKEN to REMOVED_TOKEN
 * This should only be called after advertiseRemoving
 *
 * @param endpoint
 * @param hostId
 */
public void advertiseTokenRemoved(InetAddress endpoint, UUID hostId)
{
    EndpointState epState = endpointStateMap.get(endpoint);
    epState.updateTimestamp(); // make sure we don't evict it too soon
    epState.getHeartBeatState().forceNewerGenerationUnsafe();
    long expireTime = computeExpireTime();
    epState.addApplicationState(ApplicationState.STATUS, StorageService.instance.valueFactory.removedNonlocal(hostId, expireTime));
    logger.info("Completing removal of " + endpoint);
    addExpireTimeForEndpoint(endpoint, expireTime);
    endpointStateMap.put(endpoint, epState);
    // ensure at least one gossip round occurs before returning
    Uninterruptibles.sleepUninterruptibly(intervalInMillis * 2, TimeUnit.MILLISECONDS);
}
 

实例 4


/**
 * Get the exception of a completed future.
 *
 * @param future a completed future.
 * @return the exception of a future or null if no exception was thrown
 * @throws IllegalStateException if the future is not completed.
 */
public static Throwable getException(ListenableFuture<?> future) {
  checkCompleted(future);
  try {
    Uninterruptibles.getUninterruptibly(future);
    return null;
  } catch (ExecutionException e) {
    return e.getCause();
  }
}
 

实例 5


/**
 * 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) {
  final LoadingValueReference<K, V> loadingValueReference =
      insertLoadingValueReference(key, hash);
  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;
}
 

实例 6


/**
 * 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;
}
 

实例 7


/**
 * 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;
}
 

实例 8


public void index(final IndexerTask task) {
  if (enabled) {
    final long requestedAt = System.currentTimeMillis();
    Future submit = executor.submit(new Runnable() {
      @Override
      public void run() {
        if (lastUpdatedAt == -1L) {
          lastUpdatedAt = esClient.getMaxFieldValue(indexName, typeName, dateFieldName);
        }
        if (requestedAt > lastUpdatedAt) {
          long l = task.index(lastUpdatedAt);
          // l can be 0 if no documents were indexed
          lastUpdatedAt = Math.max(l, lastUpdatedAt);
        }
      }
    });
    try {
      Uninterruptibles.getUninterruptibly(submit);
    } catch (ExecutionException e) {
      Throwables.propagate(e);
    }
  }
}
 

实例 9


protected void internalStop() {
  if (leaderElection != null) {
    // NOTE: if was a leader this will cause loosing of leadership which in callback 上面 will
    //       de-register service in discovery service and stop the service if needed
    try {
      Uninterruptibles.getUninterruptibly(leaderElection.stop(), 5, TimeUnit.SECONDS);
    } catch (TimeoutException te) {
      LOG.warn("Timed out waiting for leader election cancellation to complete");
    } catch (ExecutionException e) {
      LOG.error("Exception when cancelling leader election.", e);
    }
  }
}
 

实例 10


private void close() throws IOException {
  LOG.info("SSTables built. Now starting streaming");
  heartbeat.startHeartbeat();
  try {
    if (writer != null) {
      writer.close();
      Future<StreamState> future =
          loader.stream(Collections.<InetAddress>emptySet(), new ProgressIndicator());
      try {
        StreamState streamState = Uninterruptibles.getUninterruptibly(future);
        if (streamState.hasFailedSession()) {
          LOG.warn("Some streaming sessions failed");
        } else {
          LOG.info("Streaming finished successfully");
        }
      } catch (ExecutionException e) {
        throw new RuntimeException("Streaming to the following hosts failed: " +
            loader.getFailedHosts(), e);
      }
    } else {
      LOG.info("SSTableWriter wasn't instantiated, no streaming happened.");
    }
  } finally {
    heartbeat.stopHeartbeat();
  }
  LOG.info("Successfully closed bulk record writer");
}
 

实例 11


@Override
public void unlock() {
  if (!lock.isHeldByCurrentThread()) {
    throw new IllegalStateException("Cannot unlock without holding a lock by thread " + Thread.currentThread());
  }
  try {
    if (lock.getHoldCount() == 1) {
      // If it is the last lock entry for this thread, remove the zk node as well.
      try {
        Uninterruptibles.getUninterruptibly(zkClient.delete(localLockNode.get()));
      } catch (ExecutionException e) {
        throw Throwables.propagate(e.getCause());
      } finally {
        localLockNode.remove();
      }
    }
  } finally {
    lock.unlock();
  }
}
 

实例 12


/**
 * 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;
}
 

实例 13


/**
 * Binds <code>server</socket> to <code>address</code>. A port is
 * chosen from this port range. If the port range is [0,0], then a
 * free port is chosen by the OS.
 *
 * @throws IOException if the bind operation fails.
 */
public Channel bind(ServerBootstrap server, InetAddress address)
    throws IOException
{
    int start = random();
    int port = start;
    do {
        try {
            ChannelFuture future = server.bind(new InetSocketAddress(address, port));
            Uninterruptibles.getUninterruptibly(future);
            return future.channel();
        } catch (ExecutionException e) {
            if (!(e.getCause() instanceof BindException)) {
                Throwables.propagateIfPossible(e.getCause(), IOException.class);
                throw Throwables.propagate(e.getCause());
            }
        }
        port = succ(port);
    } while (port != start);
    throw new BindException("No free port within range");
}
 

实例 14


@Override
protected void forceEviction(QueueName queueName, int numGroups) throws Exception {
  QueueEvictor evictor = ((LevelDBQueueClientFactory) queueClientFactory).createEvictor(queueName, numGroups);
  Transaction tx = txSystemClient.startShort();
  // There is no change, just to get the latest transaction for eviction
  txSystemClient.commit(tx);
  Uninterruptibles.getUninterruptibly(evictor.evict(tx));
}
 

实例 15


public static <T> void parallelStressTest(final T obj, final Delegates.IAction1<T> action, int numberOfThreads) {
    final Thread[] threads = new Thread[numberOfThreads];
    for (int i = 0; i < numberOfThreads; i++) {
        threads[i] = new Thread(() -> action.invoke(obj));
        threads[i].start();
    }
    for (int i = 0; i < numberOfThreads; i++) {
        threads[i].interrupt();
        Uninterruptibles.joinUninterruptibly(threads[i]);
    }
}
 
讨论
淘淘あ西西 profile image