Wait for the termination of the thread pools.

@param milliseconds  The number of milliseconds to wait
@return   true if all thread pools are terminated within time limit
@throws InterruptedException
420624
public synchronized boolean awaitTermination(long milliseconds) 
      throws InterruptedException {
    boolean result = asyncDiskService.awaitTermination(milliseconds);
    if (result) {
      LOG.info("Deleting toBeDeleted directory.");
      for (int v = 0; v < volumes.length; v++) {
        Path p = new Path(volumes[v], TOBEDELETED);
        try {
          localFileSystem.delete(p, true);
        } catch (IOException e) {
          LOG.warn("Cannot cleanup " + p + " " + StringUtils.stringifyException(e));
        }
      }
    }
    return result;
  }
912359
private void waitForCompletions(long timeoutMs) throws InterruptedException {
    Long completedOperation =
        this.completedOperationIds.pollFirst(timeoutMs, TimeUnit.MILLISECONDS);
    if (completedOperation != null) {
      markOperationComplete(completedOperation);
    }
  }
201402
public Retryer<R> stopAfterDelay(final long delayInMillis) {
        checkArgument(delayInMillis >= 0L, "delayInMillis must be >= 0 but is %d", delayInMillis);
        return withStopStrategy(new StopStrategy() {
            
            @Override public boolean shouldStop(int previousAttemptNumber, long delaySinceFirstAttemptInMillis) {
                return delaySinceFirstAttemptInMillis >= delayInMillis;
            }
        });
    }
110342
void halt (final boolean wait)
  {
    synchronized (m_aSigLock)
    {
      m_aHalted.set (true);

      if (m_bPaused)
      {
        m_aSigLock.notifyAll ();
      }
      else
      {
        signalSchedulingChange (0);
      }
    }

    if (wait)
    {
      boolean interrupted = false;
      try
      {
        while (true)
        {
          try
          {
            join ();
            break;
          }
          catch (final InterruptedException ex)
          {
            interrupted = true;
          }
        }
      }
      finally
      {
        if (interrupted)
        {
          Thread.currentThread ().interrupt ();
        }
      }
    }
  }
1072815
@Nonnull
  public static ESuccess sleep (@Nonnegative final long nMilliseconds)
  {
    ValueEnforcer.isGE0 (nMilliseconds, "MilliSeconds");

    try
    {
      Thread.sleep (nMilliseconds);
      return ESuccess.SUCCESS;
    }
    catch (final InterruptedException ex)
    {
      Thread.currentThread ().interrupt ();
      return ESuccess.FAILURE;
    }
  }
129032
@SuppressWarnings({ "PMD.CollapsibleIfStatements",
        "PMD.GuardLogStatement" })
    public void awaitExhaustion() throws InterruptedException {
        synchronized (this) {
            if (generators != null) {
                if (running != generators.size()) {
                    generatorTracking
                        .severe(() -> "Generator count doesn't match tracked.");
                }
            }
            while (running > 0) {
                if (generators != null) {
                    generatorTracking
                        .fine(() -> "Thread " + Thread.currentThread().getName()
                            + " is waiting, " + generators.size()
                            + " generators registered: "
                            + generators.keySet());
                }
                wait();
            }
            generatorTracking
                .finest("Thread " + Thread.currentThread().getName()
                    + " continues.");
        }
    }
549572
public void waitThreadStopped() { // FIXME: method named in confusing way
        long sleepTime = threads.isEmpty() ? DEFAULT_TEMPORISATION : MIN_CHECK_TIME;
        lock.lock();
        try {
             condition.await(sleepTime, TimeUnit.MILLISECONDS); // NOSONAR 
        } catch (InterruptedException e) {
            log.debug("Interrupted", e);
            Thread.currentThread().interrupt();
        } finally {
            lock.unlock();
        }
    }
36310
private static boolean tryReadLockMillis(long address, long timeInMillis, boolean interruptible)
            throws InterruptedException {
        long lastTime = System.currentTimeMillis();
        do {
            if (LOCK.tryReadLock(A, null, address + LOCK_OFFSET))
                return true;
            checkInterrupted(interruptible);
            ThreadHints.onSpinWait();
            long now = System.currentTimeMillis();
            if (now != lastTime) {
                lastTime = now;
                timeInMillis--;
            }
        } while (timeInMillis >= 0);
        return false;
    }
604154
public void close() throws InterruptedException {
    synchronized (this) {
      Pools.remove(this);
      poolState.set(POOL_STATE_CLOSING);
      pendingRequestNumber.set(0);

      scheduledFuture.cancel(false);
      connectionAppender.shutdown();

      try {
        connectionAppender.awaitTermination(10, TimeUnit.SECONDS);
      } catch (InterruptedException i) {
        //eat
      }

      if (logger.isInfoEnabled()) {
        logger.info("closing pool {} (total:{}, active:{}, pending:{})",
            poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get());
      }

      ExecutorService connectionRemover = new ThreadPoolExecutor(totalConnection.get(),
          options.maxPoolSize, 10, TimeUnit.SECONDS,
          new LinkedBlockingQueue<>(options.maxPoolSize),
          new MariaDbThreadFactory(poolTag + "-destroyer"));

      //loop for up to 10 seconds to close not used connection
      long start = System.nanoTime();
      do {
        closeAll(connectionRemover, idleConnections);
        if (totalConnection.get() > 0) {
          Thread.sleep(0, 10_00);
        }
      } while (totalConnection.get() > 0
          && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start) < 10);

      //after having wait for 10 seconds, force removal, even if used connections
      if (totalConnection.get() > 0 || idleConnections.isEmpty()) {
        closeAll(connectionRemover, idleConnections);
      }

      connectionRemover.shutdown();
      try {
        unRegisterJmx();
      } catch (Exception exception) {
        //eat
      }
      connectionRemover.awaitTermination(10, TimeUnit.SECONDS);
    }
  }
649880
public void waitEnd(final long... timeout) {

        long start = System.currentTimeMillis();
        if (timeout.length == 1) {
            start += timeout[0];
        } else {
            start += DEFAULT_TIME_OUT;
        }

        while (!this.hasRun.get()) {
            try {
                Thread.sleep(SLEEP_TIME);
            } catch (final InterruptedException e) {
                break;
            }
            if (System.currentTimeMillis() > start) {
                break; // Break the loop after 1s to avoid freezing the thread
            }
        }

    }
563151
@Override
    public void awaitNanos(final long timeout) throws InterruptedException {
        long remaining = timeout;
        queueLock.lock();
        try {
            while(test() && remaining > 0) {
                remaining = condition.awaitNanos(remaining);
            }
        }
        finally {
            queueLock.unlock();
        }
    }
927929
public void stop(int waitMillis) throws InterruptedException {
    try {
      if (!isDone()) {
        setExitStatus(new Event(EventType.STOPPED_BY_USER, String.format("Stopped by user: waiting for %d ms", waitMillis)));
      }
      if (!waitForFinish(waitMillis)) {
        logger.warn("{} Client thread failed to finish in {} millis", name, waitMillis);
      }
    } finally {
      rateTracker.shutdown();
    }
  }
549264
@Override
    public final synchronized void stopService(long millis) {
        running = false;
        try {
            if (keepRunning) {
                keepRunning = false;
                interrupt();
                quit();
                if (0L == millis) {
                    join();
                } else {
                    join(millis);
                }
            }
        } catch (InterruptedException e) {
            //its possible that the thread exits between the lines keepRunning=false and interrupt above
            log.warn("Got interrupted while stopping {}", this, e);

            Thread.currentThread().interrupt();
        }
    }
12959
public boolean waitFor() throws InterruptedException {
    try {
      // [START ]
      Job completedJob = job.waitFor();
      if (completedJob == null) {
        // job no longer exists
      } else if (completedJob.getStatus().getError() != null) {
        // job failed, handle error
      } else {
        // job completed successfully
      }
      // [END ]
    } catch (BigQueryException e) {
      // Timeouts shouldn't happen without a timeout option.
      if (e.getCause() instanceof PollException) {
        return false;
      }
      throw e;
    }
    return true;
  }
698486
private Object waitForResult(long timeoutMillis)
                    throws ExecutionException, InterruptedException, TimeoutException, RemoteException { // F16043
        final boolean isTraceOn = svLogger.isLoggable(Level.FINER);
        if (isTraceOn)
            svLogger.entering(CLASS_NAME, "waitForResult", Long.valueOf(timeoutMillis));

        long begin = System.nanoTime();
        // The nanoTime updated before every call to
        // RemoteAsyncResultExtended.waitForResult.
        long beginLastAttempt = begin;
        // The nanoTime when we should stop waiting altogether.  This value is
        // only used if timeout is non-zero.
        long end = begin + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);

        // True if the client ORB has ever thrown a NO_RESPONSE.
        boolean noResponse = false;
        // The waitTime argument for the next call to
        // RemoteAsyncResultExtended.waitForResult.
        long waitTimeMillis = timeoutMillis;
        // The maximum value for waitTimeMillis.  This value is lazily
        // initialized when a NO_RESPONSE occurs.
        long maxWaitTimeMillis = -1;

        for (;;) {
            if (isTraceOn)
                svLogger.entering(CLASS_NAME, "waitForResult", "waiting " + waitTimeMillis);

            Object[] resultArray;
            try {
                resultArray = stubWaitForResult((Stub) ivServer, waitTimeMillis);
            } catch (RemoteException ex) {
                Throwable cause = ex.getCause();

                // If this is the first NO_RESPONSE, then try again with a shorter
                // server-side wait time.  For subsequent NO_RESPONSE, assume there
                // is a connection issue and rethrow the exception.
                if (cause instanceof NO_RESPONSE && !noResponse) {
                    if (isTraceOn)
                        svLogger.logp(Level.FINER, CLASS_NAME, "waitForResult", "retrying", cause);
                    resultArray = null;
                    noResponse = true;
                } else {
                    if (isTraceOn)
                        svLogger.exiting(CLASS_NAME, "waitForResult", ex);
                    throw ex;
                }
            }

            if (resultArray != null) {
                if (isTraceOn)
                    svLogger.exiting(CLASS_NAME, "waitForResult", "result");
                return resultArray[0];
            }

            // Either the client ORB or the server timed us out.  Choose a lower
            // waitTimeMillis and then try again.

            long now = System.nanoTime();

            if (timeoutMillis > 0) {
                long remainingMillis = TimeUnit.NANOSECONDS.toMillis(end - now);
                if (remainingMillis <= 0) {
                    if (isTraceOn)
                        svLogger.exiting(CLASS_NAME, "waitForResult", "timeout");
                    throw new TimeoutException();
                }

                waitTimeMillis = remainingMillis;
            }

            if (noResponse) {
                if (maxWaitTimeMillis == -1) {
                    // For the first NO_RESPONSE, set maximum server wait time for
                    // all subsequent requests based on how long the ORB actually
                    // waited before timing out this request.  Back off a little bit
                    // to give time for the server to respond.
                    long actualWaitTimeMillis = TimeUnit.NANOSECONDS.toMillis(now - beginLastAttempt);
                    maxWaitTimeMillis = Math.max(MIN_ASYNC_RESULT_NO_RESPONSE_WAIT_TIME,
                                                 actualWaitTimeMillis - AsyncResultNoResponseBackoff);
                }

                if (timeoutMillis == 0) {
                    waitTimeMillis = maxWaitTimeMillis;
                } else {
                    waitTimeMillis = Math.min(waitTimeMillis, maxWaitTimeMillis);
                }
            }

            beginLastAttempt = now;
        }
    }
650549
@SuppressWarnings({ "PMD.CollapsibleIfStatements",
        "PMD.GuardLogStatement" })
    public boolean awaitExhaustion(long timeout)
            throws InterruptedException {
        synchronized (this) {
            if (generators != null) {
                if (running != generators.size()) {
                    generatorTracking.severe(
                        "Generator count doesn't match tracked.");
                }
            }
            if (isExhausted()) {
                return true;
            }
            if (generators != null) {
                generatorTracking
                    .fine(() -> "Waiting, generators: " + generators.keySet());
            }
            wait(timeout);
            if (generators != null) {
                generatorTracking
                    .fine(() -> "Waited, generators: " + generators.keySet());
            }
            return isExhausted();
        }
    }
764109
public static void pause(long milli) {
		final Thread t = Thread.currentThread();
		long start = System.currentTimeMillis();
		while( System.currentTimeMillis() - start < milli ) {
			synchronized( t )  {
				try {
					long target = milli - (System.currentTimeMillis() - start);
					if( target > 0 )
						t.wait(target);
				} catch (InterruptedException ignore) {
				}
			}
		}
	}