Prepare the executor for shutdown.

@param respMap json response object
2474
private void shutdown(final Map<String, Object> respMap) {
    try {
      logger.warn("Shutting down executor...");

      // Set the executor to inactive. Will receive no new flows.
      setActiveInternal(false);
      this.application.shutdown();
      respMap.put(ConnectorParams.STATUS_PARAM, ConnectorParams.RESPONSE_SUCCESS);
    } catch (final Exception e) {
      logger.error(e.getMessage(), e);
      respMap.put(ConnectorParams.RESPONSE_ERROR, e.getMessage());
    }
  }
70793
@Override
  public void initialize(String name, final Scheduler scheduler) throws SchedulerException {

    logger.info("Registering Quartz shutdown hook.");

    Thread t =
        new Thread("Quartz Shutdown-Hook") {

          @Override
          public void run() {

            logger.info("Shutting down Quartz...");
            try {
              scheduler.shutdown();
            } catch (SchedulerException e) {
              logger.info("Error shutting down Quartz: " + e.getMessage(), e);
            }
          }
        };

    Runtime.getRuntime().addShutdownHook(t);
  }
547446
private static ExecutorService wrapExecutor(final Executor executor)
    {
        return new AbstractExecutorService()
        {
            private volatile boolean isShutdown = false;
            private volatile boolean isTerminated = false;

            @Override
            public void shutdown()
            {
                isShutdown = true;
            }

            @Override
            public List<Runnable> shutdownNow()
            {
                return Lists.newArrayList();
            }

            @Override
            public boolean isShutdown()
            {
                return isShutdown;
            }

            @Override
            public boolean isTerminated()
            {
                return isTerminated;
            }

            @Override
            public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException
            {
                throw new UnsupportedOperationException();
            }

            @Override
            public void execute(Runnable command)
            {
                try
                {
                    executor.execute(command);
                }
                finally
                {
                    isShutdown = true;
                    isTerminated = true;
                }
            }
        };
    }
1291143
public synchronized final void shutdown() throws RepositoryException {
        preShutdown();

        delegateWriter = NoOpQueryIndexWriter.INSTANCE;
        try {
            // Shutdown each of the provided indexes ...
            for (Map<String, AtomicIndex> byWorkspaceName : providedIndexesByWorkspaceNameByIndexName.values()) {
                for (AtomicIndex provided : byWorkspaceName.values()) {
                    provided.shutdown(false);
                }
            }
        } finally {
            providedIndexesByWorkspaceNameByIndexName.clear();
            providedIndexesByIndexNameByWorkspaceName.clear();
            postShutdown();
        }
    }
403135
public void shutdown() {
        workerGroup.shutdownGracefully().syncUninterruptibly();
        bossGroup.shutdownGracefully().syncUninterruptibly();
        getExecutionContext().getEventBus().post(new JNRPEStatusEvent(STATUS.STOPPED, this, "JNRPE Server stopped"));
    }
125910
@GuardedBy("lock")
	private CompletableFuture<Void> shutDownResourceManagerComponents() {

		final Collection<CompletableFuture<Void>> terminationFutures = new ArrayList<>(dispatcherResourceManagerComponents.size());

		for (DispatcherResourceManagerComponent<?> dispatcherResourceManagerComponent : dispatcherResourceManagerComponents) {
			terminationFutures.add(dispatcherResourceManagerComponent.closeAsync());
		}

		final FutureUtils.ConjunctFuture<Void> dispatcherTerminationFuture = FutureUtils.completeAll(terminationFutures);

		return FutureUtils.runAfterwards(
			dispatcherTerminationFuture,
			() -> {
				Exception exception = null;

				synchronized (lock) {
					if (resourceManagerLeaderRetriever != null) {
						try {
							resourceManagerLeaderRetriever.stop();
						} catch (Exception e) {
							exception = ExceptionUtils.firstOrSuppressed(e, exception);
						}

						resourceManagerLeaderRetriever = null;
					}

					if (dispatcherLeaderRetriever != null) {
						try {
							dispatcherLeaderRetriever.stop();
						} catch (Exception e) {
							exception = ExceptionUtils.firstOrSuppressed(e, exception);
						}

						dispatcherLeaderRetriever = null;
					}

					if (webMonitorLeaderRetrievalService != null) {
						try {
							webMonitorLeaderRetrievalService.stop();
						} catch (Exception e) {
							exception = ExceptionUtils.firstOrSuppressed(e, exception);
						}

						webMonitorLeaderRetrievalService = null;
					}
				}

				if (exception != null) {
					throw exception;
				}
			});
	}
426760
public static void prepare() throws InterruptedException {
		semaphore.acquire();
		if (cacheReference == masterCache) {
			slaveCache.clear();
		} else {
			masterCache.clear();
		}
	}
459352
private void shutdownExecutorGroups(long quietPeriod, long timeout, TimeUnit unit, EventExecutorGroup...groups) {
    Exception ex = null;
    List<Future<?>> futures = new ArrayList<>();
    for (EventExecutorGroup group : groups) {
      if (group == null) {
        continue;
      }
      futures.add(group.shutdownGracefully(quietPeriod, timeout, unit));
    }

    for (Future<?> future : futures) {
      try {
        future.syncUninterruptibly();
      } catch (Exception e) {
        if (ex == null) {
          ex = e;
        } else {
          ex.addSuppressed(e);
        }
      }
    }

    if (ex != null) {
      // Just log, don't rethrow since it shouldn't happen normally and
      // there is nothing much can be done from the caller side
      LOG.warn("Exception raised when shutting down executor", ex);
    }
  }
940937
def shutdown(self, timeout=None):
        """"""
        try:
            super(BaseDrmaaManager, self).shutdown(timeout)
        except Exception:
            pass
        self.drmaa_session.close()
1253640
@Override
    public synchronized void shutdown()
    {
        // prevent reentrant invocation
        if(isShutdown())
            return;

        // create a temporary set of providers to shutdown after completing all the pin instance shutdowns
        Set<GpioProvider> gpioProvidersToShutdown = new HashSet<>();

        // shutdown explicit configured GPIO pins
        for (GpioPin pin : pins) {

            // add each GPIO provider to the shutdown set
            if(!gpioProvidersToShutdown.contains(pin.getProvider())){
                gpioProvidersToShutdown.add(pin.getProvider());
            }

            // perform the shutdown options if configured for the pin
            GpioPinShutdown shutdownOptions = pin.getShutdownOptions();
            if (shutdownOptions != null) {
                // get shutdown option configuration
                PinState state = shutdownOptions.getState();
                PinMode mode = shutdownOptions.getMode();
                PinPullResistance resistance = shutdownOptions.getPullResistor();
                Boolean unexport = shutdownOptions.getUnexport();

                // perform shutdown actions
                if ((state != null) && pin.isMode(PinMode.DIGITAL_OUTPUT)) {
                    ((GpioPinDigitalOutput)pin).setState(state);
                }
                if (resistance != null) {
                    pin.setPullResistance(resistance);
                }
                if (mode != null) {
                    pin.setMode(mode);
                }
                if (unexport != null && unexport == Boolean.TRUE) {
                    pin.unexport();
                }
            }
        }

        // perform a shutdown on each GPIO provider
        for(GpioProvider gpioProvider : gpioProvidersToShutdown){
            if(!gpioProvider.isShutdown()){
                gpioProvider.shutdown();
            }
        }

        // shutdown all executor services
        //
        // NOTE: we are not permitted to access the shutdown() method of the individual
        // executor services, we must perform the shutdown with the factory
        GpioFactory.getExecutorServiceFactory().shutdown();

        // set is shutdown tracking variable
        isshutdown = true;
    }
396434
private static void safeSetRemoveOnCancel(ScheduledThreadPoolExecutor executor) {
        try {
            executor.getClass().getMethod("setRemoveOnCancelPolicy", boolean.class).invoke(executor, Boolean.TRUE);
        } catch (IllegalAccessException e) {
            throwSetRemoveOnCancelException(e);
        } catch (IllegalArgumentException e) {
            throwSetRemoveOnCancelException(e);
        } catch (InvocationTargetException e) {
            throwSetRemoveOnCancelException(e.getCause());
        } catch (NoSuchMethodException e) {
            throw new SdkClientException("The request timeout feature is only available for Java 1.7 and above.");
        } catch (SecurityException e) {
            throw new SdkClientException("The request timeout feature needs additional permissions to function.", e);
        }
    }
983013
protected void stopServing() throws Exception {
    if (isServing()) {
      if (!mGrpcServer.shutdown()) {
        LOG.warn("RPC Server shutdown timed out.");
      }
    }
    if (mRPCExecutor != null) {
      mRPCExecutor.shutdown();
      try {
        mRPCExecutor.awaitTermination(
            ServerConfiguration.getMs(PropertyKey.MASTER_GRPC_SERVER_SHUTDOWN_TIMEOUT),
            TimeUnit.MILLISECONDS);
      } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
      } finally {
        mRPCExecutor.shutdownNow();
      }
    }
    if (mJvmPauseMonitor != null) {
      mJvmPauseMonitor.stop();
    }
    if (mWebServer != null) {
      mWebServer.stop();
      mWebServer = null;
    }
    MetricsSystem.stopSinks();
  }
742906
private static void shutdown(ExecutorService executorService) {
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
                if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                    System.err.println("Thread pool did not terminate");
                }
            }
        } catch (InterruptedException ie) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
1337506
public void prepareForShutdown() {
        Collection<CompletableFuture<Void>> prepareShutdownFutures = shutdownListeners.stream()
                                                                                      .map(shutdownListener -> CompletableFuture.runAsync(() -> shutdownListener.prepareForShutdown()))
                                                                                      .collect(Collectors.toList());
        try {
            CompletableFuture.allOf(prepareShutdownFutures.toArray(new CompletableFuture[prepareShutdownFutures.size()]))
                             .get(prepareForShutdownTimeoutSec, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("Exception occurred while preparing shutdown.", e);
        }
    }
1075429
@Override
  public void close() throws Exception {
    LOG.log(Level.FINE, "close");

    if (this.executor != null) {
      this.executor.shutdown();
      try {
        // wait for threads to finish for timeout
        if (!executor.awaitTermination(shutdownTimeout, TimeUnit.MILLISECONDS)) {
          LOG.log(Level.WARNING, "Executor did not terminate in {0} ms.", shutdownTimeout);
          final List<Runnable> droppedRunnables = executor.shutdownNow();
          LOG.log(Level.WARNING, "Executor dropped {0} tasks.", droppedRunnables.size());
        }
      } catch (final InterruptedException e) {
        LOG.log(Level.WARNING, "Close interrupted", e);
        throw new RemoteRuntimeException(e);
      }
    }
  }
1307407
private void closeSoon() {
        isClosing.set(true);
        @NotNull ScheduledExecutorService closer = newSingleThreadScheduledExecutor(new NamedThreadFactory("closer", true));
        closer.schedule(() -> {
            closer.shutdown();
            close();
        }, 2, SECONDS);
    }
680844
public void shutdown() {
        if (!isRunning) return;

        Executors.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                if (mHttpServer != null) {
                    mHttpServer.shutdown(3, TimeUnit.MINUTES);
                    isRunning = false;
                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onStopped();
                        }
                    });
                }
            }
        });
    }