State check needed by ScheduledThreadPoolExecutor to
enable running tasks during shutdown.

@param shutdownOK true if should return true if SHUTDOWN
517009
final boolean isRunningOrShutdown(boolean shutdownOK) {
        int rs = runStateOf(ctl.get());
        return rs == RUNNING || (rs == SHUTDOWN && shutdownOK);
    }
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;
		}
	}
445377
public void shutdown() {
	    if (shutdown) 
	    {
	        return;
	    }
	    shutdown = true;
	    synchronized (workers) 
	    {
	        for (int i = workers.size(); i > 0; i--) 
	        {
	        	systemExecute(exitTask);
	        }
	        waitConditionStrategy.signalAllWhenBlocking();
	    }
	}
120419
public static synchronized void addOperation(Runnable runnable, boolean preserveForNextShutdown) {
        shutdownOperations.add(runnable);
        if(preserveForNextShutdown) {
            preservedShutdownOperations.add(runnable);
        }
    }
1254294
public static void shutdownAndAwaitTermination() {
		shutdown();
		if (pool != null) {
			try {
				// wait a while for existing tasks to terminate
				if (!pool.awaitTermination(60L, TimeUnit.SECONDS)) {
					pool.shutdownNow(); // cancel currently executing tasks
					// wait a while for tasks to respond to being canceled
					if (!pool.awaitTermination(60L, TimeUnit.SECONDS)) {
						logger.warn("BioJava ConcurrencyTools thread pool did not terminate");
					}
				}
			} catch (InterruptedException ie) {
				pool.shutdownNow(); // (re-)cancel if current thread also interrupted
				Thread.currentThread().interrupt(); // preserve interrupt status
			}
		}
	}
874588
public void shutdown() {
        // as resources are returned we need to shut them down
        T t;
        synchronized (lock) {
            isRunning = false;
            t = idleResources.poll();
        }
        while (t != null) {
            returnResource(t, true);
            synchronized (lock) {
                t = idleResources.poll();
            }
        }
    }
465955
@Override
  protected void shutDown()
      throws Exception {
    this.scheduledExecutorPool.shutdown();
    this.scheduledExecutorPool.awaitTermination(TERMINATION_TIMEOUT, TimeUnit.SECONDS);
    this.jobStatusMonitor.shutDown();
  }
273420
protected boolean confirmShutdown() {
        if (!isShuttingDown()) {
            return false;
        }

        if (!inEventLoop()) {
            throw new IllegalStateException("must be invoked from an event loop");
        }

        cancelScheduledTasks();

        if (gracefulShutdownStartTime == 0) {
            gracefulShutdownStartTime = ScheduledFutureTask.nanoTime();
        }

        if (runAllTasks() || runShutdownHooks()) {
            if (isShutdown()) {
                // Executor shut down - no new tasks anymore.
                return true;
            }

            // There were tasks in the queue. Wait a little bit more until no tasks are queued for the quiet period or
            // terminate if the quiet period is 0.
            // See https://github.com/netty/netty/issues/4241
            if (gracefulShutdownQuietPeriod == 0) {
                return true;
            }
            wakeup(true);
            return false;
        }

        final long nanoTime = ScheduledFutureTask.nanoTime();

        if (isShutdown() || nanoTime - gracefulShutdownStartTime > gracefulShutdownTimeout) {
            return true;
        }

        if (nanoTime - lastExecutionTime <= gracefulShutdownQuietPeriod) {
            // Check if any tasks were added to the queue every 100ms.
            // TODO: Change the behavior of takeTask() so that it returns on timeout.
            wakeup(true);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // Ignore
            }

            return false;
        }

        // No tasks were added for last quiet period - hopefully safe to shut down.
        // (Hopefully because we really cannot make a guarantee that there will be no execute() calls by a user.)
        return true;
    }
920873
public void shutdown() {
    if (shutdown) {
      return;
    }
    cache.clear();
    stats.shutdown();
    dispatcher.shutdown();
    if (closeableCache != null) {
      try {
        closeableCache.close();
      } catch (IOException ignored) {
      }
    }
    for (DeferredRequestCreator deferredRequestCreator : targetToDeferredRequestCreator.values()) {
      deferredRequestCreator.cancel();
    }
    targetToDeferredRequestCreator.clear();
    shutdown = true;
  }
1033384
def on_shutdown(self, callback: callable, polling=True, webhook=True):
        
        self._check_frozen()
        if not webhook and not polling:
            warn('This action has no effect!', UserWarning)
            return

        if isinstance(callback, (list, tuple, set)):
            for cb in callback:
                self.on_shutdown(cb, polling, webhook)
            return

        if polling:
            self._on_shutdown_polling.append(callback)
        if webhook:
            self._on_shutdown_webhook.append(callback)
1154217
private void allowCleanShutdown() {
        DelayingShutdownHook hook = new DelayingShutdownHook();
        Context context = (Context) this.loggerFactory;
        hook.setContext(context);
        Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]");
        Runtime.getRuntime().addShutdownHook(hookThread);
    }
970150
@Override
  public ManagedChannelImpl shutdown() {
    channelLogger.log(ChannelLogLevel.DEBUG, "shutdown() called");
    if (!shutdown.compareAndSet(false, true)) {
      return this;
    }

    // Put gotoState(SHUTDOWN) as early into the syncContext's queue as possible.
    // delayedTransport.shutdown() may also add some tasks into the queue. But some things inside
    // delayedTransport.shutdown() like setting delayedTransport.shutdown = true are not run in the
    // syncContext's queue and should not be blocked, so we do not drain() immediately here.
    final class Shutdown implements Runnable {
      @Override
      public void run() {
        channelLogger.log(ChannelLogLevel.INFO, "Entering SHUTDOWN state");
        channelStateManager.gotoState(SHUTDOWN);
      }
    }

    syncContext.executeLater(new Shutdown());

    uncommittedRetriableStreamsRegistry.onShutdown(SHUTDOWN_STATUS);
    final class CancelIdleTimer implements Runnable {
      @Override
      public void run() {
        cancelIdleTimer(/* permanent= */ true);
      }
    }

    syncContext.execute(new CancelIdleTimer());
    return this;
  }
395266
def consumer_shutdown_task(processor, check_point_tracker):
    
    exception = None
    try:
        processor.shutdown(check_point_tracker)
    except Exception as e:
        print(e)
        exception = None

    try:
        check_point_tracker.get_check_point()
    except Exception:
        logger.error('Failed to flush check point', exc_info=True)

    return TaskResult(exception)
1076207
private void shutdownImpl(ShutdownModeAmp mode, 
                            ExitCode exitCode,
                            Result<String> result)
  {
    // start the fail-safe thread in case the shutdown fails
    FailSafeHaltThread haltThread = _failSafeHaltThread;
    
    if (haltThread != null) {
      haltThread.startShutdown();
    }

    if (exitCode == null) {
      exitCode = ExitCode.FAIL_SAFE_HALT;
    }
    
    _exitCode.compareAndSet(null, exitCode);

    try {
      SystemManager systemManager = _systemManagerRef.get();
        
      if (systemManager != null) {
        systemManager.shutdown(mode);
      }
    } catch (Throwable e) {
      log.log(Level.WARNING, e.toString(), e);
    } finally {
      _systemManagerRef = null;
      _lifecycle.toDestroy();

      System.err.println("\nShutdown reason: " + exitCode + "\n");

      log.warning("Shutdown reason: " + exitCode);
      
      if (result != null) {
        result.ok("Shutdown reason: " + exitCode);
      }

      if (! _isEmbedded) {
        System.exit(exitCode.ordinal());
      }
    }
  }
199322
public void shutdown() {
        // shutdown each single thread executor in the managed collection
        for (ExecutorService singleThreadExecutorService : singleThreadExecutorServices) {
            shutdownExecutor(singleThreadExecutorService);
        }

        // shutdown scheduled executor instance
        shutdownExecutor(getInternalScheduledExecutorService());
        shutdownExecutor(getInternalGpioExecutorService());

    }
566853
@SuppressWarnings({"deprecation", "WeakerAccess"})
  protected void removeShutdownHook(ClassLoaderLeakPreventor preventor, Thread shutdownHook) {
    final String displayString = "'" + shutdownHook + "' of type " + shutdownHook.getClass().getName();
    preventor.error("Removing shutdown hook: " + displayString);
    Runtime.getRuntime().removeShutdownHook(shutdownHook);

    if(executeShutdownHooks) { // Shutdown hooks should be executed
      
      preventor.info("Executing shutdown hook now: " + displayString);
      // Make sure it's from protected ClassLoader
      shutdownHook.start(); // Run cleanup immediately
      
      if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish
        try {
          shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run
        }
        catch (InterruptedException e) {
          // Do nothing
        }
        if(shutdownHook.isAlive()) {
          preventor.warn(shutdownHook + "still running after " + shutdownHookWaitMs + " ms - Stopping!");
          shutdownHook.stop();
        }
      }
    }
  }
351012
public void shutdown() {
    if (this == singleton) {
      throw new UnsupportedOperationException("Default singleton instance cannot be shutdown.");
    }
    if (shutdown) {
      return;
    }
    application.unregisterActivityLifecycleCallbacks(activityLifecycleCallback);
    // Only supplied by us for testing, so it's ok to shut it down. If we were to make this public,
    // we'll have to add a check similar to that of AnalyticsNetworkExecutorService below.
    analyticsExecutor.shutdown();
    if (networkExecutor instanceof AnalyticsNetworkExecutorService) {
      networkExecutor.shutdown();
    }
    stats.shutdown();
    shutdown = true;
    synchronized (INSTANCES) {
      INSTANCES.remove(tag);
    }
  }