Do a two-phase/two-attempts shutdown
@param pool	the thread pool
@param waitSeconds	number of seconds to wait in each of the shutdown attempts
@return	true if shutdown completed, false if not
7438
public static boolean shutdownAndAwaitTermination(ExecutorService pool, long waitSeconds) {
		pool.shutdown(); // Disable new tasks from being submitted
		try {
			// Wait a while for existing tasks to terminate
			if(!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) {
				//logger.warn("Thread pool is still running: {}", pool);
				pool.shutdownNow(); // Cancel currently executing tasks
				// Wait a while for tasks to respond to being cancelled
				if(!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)){
					//logger.warn("Thread pool is not terminating: {}", pool);
					return false;
				}else{
					return true;
				}
			}else{
				return true;
			}
		} catch(InterruptedException ie) {
			// (Re-)Cancel if current thread also interrupted
			pool.shutdownNow();
			// Preserve interrupt status
			Thread.currentThread().interrupt();
			return false;
		}
	}
721017
@Override
    @GuardedBy("hudson.model.Queue.lock")
    public long check(final AbstractCloudComputer c) {
        final AbstractCloudSlave computerNode = c.getNode();
        if (c.isIdle() && computerNode != null) {
            final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();
            if (idleMilliseconds > MINUTES.toMillis(idleMinutes)) {
                LOG.info("Disconnecting {}, after {} min timeout.", c.getName(), idleMinutes);
                try {
                    computerNode.terminate();
                } catch (InterruptedException | IOException e) {
                    LOG.warn("Failed to terminate {}", c.getName(), e);
                }
            }
        }
        return 1;
    }
1254120
def queue(action, *args)
      raise PoolClosed.new("Pool #{self} is currently closed") if pool_closed?
      raise ArgumentError.new('Expecting block') unless action.is_a?(Proc)
      @lock.synchronize do
        @queue << [action, args]
        create_thread
      end
    end
1245047
@Override
  public void close() throws Exception {
    if (closed.compareAndSet(false, true)) {
      executor.shutdown();
      completionExecutor.shutdown();
      if (!executor.awaitTermination(shutdownTimeout, TimeUnit.MILLISECONDS)) {
        LOG.log(Level.WARNING, "Executor did not terminate in " + shutdownTimeout + "ms.");
        final List<Runnable> droppedRunnables = executor.shutdownNow();
        LOG.log(Level.WARNING, "Executor dropped " + droppedRunnables.size() + " tasks.");
      }
      if (!completionExecutor.awaitTermination(shutdownTimeout, TimeUnit.MILLISECONDS)) {
        LOG.log(Level.WARNING, "Executor did not terminate in " + shutdownTimeout + "ms.");
        final List<Runnable> droppedRunnables = completionExecutor.shutdownNow();
        LOG.log(Level.WARNING, "Completion executor dropped " + droppedRunnables.size() + " tasks.");
      }
    }
  }
608261
def shutdown(self, wait=True):
    

    if self.__running:
      # Add a Non-entry for every worker thread we have.
      for thread in self.__threads:
        assert thread.isAlive()
        self.__queue.append(None)
      self.__running = False

    if wait:
      self.__queue.wait()
      for thread in self.__threads:
        thread.join()
339424
public static void forkJoinExecution(Runnable runnable, ConcurrencyConfiguration concurrencyConfiguration, boolean parallelStream) {
        if(parallelStream && concurrencyConfiguration.isParallelized()) {
            try {
                ForkJoinPool pool = new ForkJoinPool(concurrencyConfiguration.getMaxNumberOfThreadsPerTask());
                pool.submit(runnable).get();
                pool.shutdown();
            } 
            catch (InterruptedException | ExecutionException ex) {
                throw new RuntimeException(ex);
            }
        }
        else {
            runnable.run();
        }
    }
647039
private void shutdownAndAwaitTermination( ExecutorService pool, int queueSize )
    {
        log.info( "Shutting down executor service; queue size={}.", queueSize );

        pool.shutdown(); // Disable new tasks from being submitted

        log.info( "Waiting for executor service to finish all queued tasks." );

        try
        {
            // Wait a while for existing tasks to terminate
            if ( ! pool.awaitTermination( 60, TimeUnit.SECONDS ) )
            {
                log.info( "Executor service did not terminate before timeout; forcing shutdown." );

                List<Runnable> queuedTasks = pool.shutdownNow(); // Cancel currently executing tasks

                log.info( "Discarded {} tasks that were still queued; still waiting for executor service to terminate."
                        , queuedTasks.size() );

                // Wait a while for tasks to respond to being cancelled
                if ( ! pool.awaitTermination( 60, TimeUnit.SECONDS ) )
                {
                    log.error( "Pool did not terminate." );
                }
                else
                {
                    log.info( "Executor service terminated after forced shutdown." );
                }
            }
            else
            {
                log.info( "Executor service finished all queued tasks and terminated." );
            }
        }
        catch ( InterruptedException ie )
        {
            log.error( "Interrupted while waiting for pool to terminate; forcing shutdown.", ie );

            // (Re-)Cancel if current thread also interrupted
            List<Runnable> queuedTasks = pool.shutdownNow();

            log.info( "Discarded {} tasks that were still queued; no longer waiting for executor service to terminate."
                    , queuedTasks.size() );

            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }
882053
public void waitAllThreadComplete(int waitInMillis) {
		for (int i=0; i<pool.length; i++) {
			if (pool[i] != null && pool[i].isAlive()) {
				try {
					pool[i].join(waitInMillis);
				} catch (InterruptedException e) {
				}
			}
		}
	}
297032
def disconnect!(wait=false)
      begin
        # For backwards compatibility we disconnect/clear the pool rather
        # than close it here.
        pool.disconnect!
      rescue Error::PoolClosedError
        # If the pool was already closed, we don't need to do anything here.
      end
      monitor.stop!(wait)
      @connected = false
      true
    end
691735
public boolean waitForCondition(Condition condition, int timeout){
		final long endTime = SystemClock.uptimeMillis() + timeout;

		while (true) {
			final boolean timedOut = SystemClock.uptimeMillis() > endTime;
			if (timedOut){
				return false;
			}

			sleeper.sleep();

			if (condition.isSatisfied()){
				return true;
			}
		}
	}
339831
@Override
  public void shutdown() {
    if (!active.compareAndSet(true, false) ) {
      throw new IllegalArgumentException("shutdown() called for inactive pool: " + getName());
    }
    log.info("Shutdown triggered on {}", getName());
    Set<HClient> clients = new HashSet<HClient>();
    availableClientQueue.drainTo(clients);
    if ( clients.size() > 0 ) {
      for (HClient hClient : clients) {
        hClient.close();
      }
    }
    log.info("Shutdown complete on {}", getName());
  }
492115
public void waitForEachEventLoop() throws InterruptedException, ExecutionException
    {
        for (EventExecutor exec : serverGroup.clientToProxyWorkerPool)
        {
            exec.submit(() -> {
                // Do nothing.
            }).get();
        }
    }
465955
@Override
  protected void shutDown()
      throws Exception {
    this.scheduledExecutorPool.shutdown();
    this.scheduledExecutorPool.awaitTermination(TERMINATION_TIMEOUT, TimeUnit.SECONDS);
    this.jobStatusMonitor.shutDown();
  }
1208021
private boolean waitForRemove(long waitStart, long maxWait) throws InterruptedException {
        if (this.size == this.capacity) {
            if (!waitOnCondition(this.notFull, maxWait, waitStart)) {
                return false;
            }
        }

        return true;
    }
821995
public void shutdown() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            /* J2ObjC removed.
            checkShutdownAccess();
            */
            advanceRunState(SHUTDOWN);
            interruptIdleWorkers();
            onShutdown(); // hook for ScheduledThreadPoolExecutor
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
    }
445377
public void shutdown() {
	    if (shutdown) 
	    {
	        return;
	    }
	    shutdown = true;
	    synchronized (workers) 
	    {
	        for (int i = workers.size(); i > 0; i--) 
	        {
	        	systemExecute(exitTask);
	        }
	        waitConditionStrategy.signalAllWhenBlocking();
	    }
	}
399309
public boolean waitForActive(long timeout)
  {
    LifecycleState state = getState();

    if (state.isActive()) {
      return true;
    }
    else if (state.isAfterActive()) {
      return false;
    }
    
    // server/1d2j
    long waitEnd = CurrentTime.getCurrentTimeActual() + timeout;

    synchronized (this) {
      while ((state = _state).isBeforeActive()
             && CurrentTime.getCurrentTimeActual() < waitEnd) {
        if (state.isActive()) {
          return true;
        }
        else if (state.isAfterActive()) {
          return false;
        }

        try {
          long delta = waitEnd - CurrentTime.getCurrentTimeActual();
          
          if (delta > 0) {
            wait(delta);
          }
        } catch (InterruptedException e) {
        }
      }
    }
    
    return _state.isActive();
  }