Stop processing events and shut down this host instance.

@return A CompletableFuture that completes when shutdown is finished.
544414
public CompletableFuture<Void> unregisterEventProcessor() {
        TRACE_LOGGER.info(this.hostContext.withHost("Stopping event processing"));

        if (this.unregistered == null) {
            // PartitionManager is created in constructor. If this object exists, then
            // this.partitionManager is not null.
            this.unregistered = this.partitionManager.stopPartitions();

            // If we own the executor, stop it also.
            // Owned executor is also created in constructor.
            if (this.weOwnExecutor) {
                this.unregistered = this.unregistered.thenRunAsync(() -> {
                    // IMPORTANT: run this last stage in the default threadpool!
                    // If a task running in a threadpool waits for that threadpool to terminate, it's going to wait a long time...

                    // It is OK to call shutdown() here even if threads are still running.
                    // Shutdown() causes the executor to stop accepting new tasks, but existing tasks will
                    // run to completion. The pool will terminate when all existing tasks finish.
                    // By this point all new tasks generated by the shutdown have been submitted.
                    this.executorService.shutdown();

                    try {
                        this.executorService.awaitTermination(10, TimeUnit.MINUTES);
                    } catch (InterruptedException e) {
                        throw new CompletionException(e);
                    }
                }, ForkJoinPool.commonPool());
            }
        }

        return this.unregistered;
    }
1223192
@Override
  public boolean stop()
  {
    if (! _lifecycle.toStopping())
      return false;

    log.finest(this + " stopping");

    closeConnections();

    destroy();

    return true;
  }
1012988
CompletableFuture<Void> close() {
    return closeClient()
        .exceptionally(v -> null)
        .thenCompose(v -> closeServer())
        .exceptionally(v -> null);
  }
890121
@Override
    public synchronized BeanContext stop() {
        if (terminating.compareAndSet(false, true)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Stopping BeanContext");
            }
            publishEvent(new ShutdownEvent(this));

            // need to sort registered singletons so that beans with that require other beans appear first
            List<BeanRegistration> objects = topologicalSort(singletonObjects.values());

            Set<Integer> processed = new HashSet<>();
            for (BeanRegistration beanRegistration : objects) {
                BeanDefinition def = beanRegistration.beanDefinition;
                Object bean = beanRegistration.bean;
                int sysId = System.identityHashCode(bean);
                if (processed.contains(sysId)) {
                    continue;
                }

                if (LOG_LIFECYCLE.isDebugEnabled()) {
                    LOG_LIFECYCLE.debug("Destroying bean [{}] with identifier [{}]", bean, beanRegistration.identifier);
                }

                processed.add(sysId);
                if (def instanceof DisposableBeanDefinition) {
                    try {
                        //noinspection unchecked
                        ((DisposableBeanDefinition) def).dispose(this, bean);
                    } catch (Throwable e) {
                        if (LOG.isErrorEnabled()) {
                            LOG.error("Error disposing of bean registration [" + def.getName() + "]: " + e.getMessage(), e);
                        }
                    }
                }
                if (def instanceof Closeable) {
                    try {
                        ((Closeable) def).close();
                    } catch (Throwable e) {
                        if (LOG.isErrorEnabled()) {
                            LOG.error("Error disposing of bean registration [" + def.getName() + "]: " + e.getMessage(), e);
                        }
                    }
                }
                if (bean instanceof LifeCycle) {
                    ((LifeCycle) bean).stop();
                }
            }

            terminating.set(false);
            running.set(false);
            ClassLoadingReporter.finish();
        }
        return this;
    }
794383
public boolean shutdown() {
    mServer.shutdown();
    try {
      return mServer.awaitTermination(mServerShutdownTimeoutMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException ie) {
      Thread.currentThread().interrupt();
      return false;
    } finally {
      mServer.shutdownNow();
    }
  }
876761
public void stop() {
        if (future != null) {
            future.cancel(true);
        }
        if (executor != null) {
            executor.shutdownNow();
        }
    }
346056
public boolean close() {
    if (open.compareAndSet(true, false)) {
      futures.forEach(future -> future.completeExceptionally(new IllegalStateException("Closed session")));
      return true;
    }
    return false;
  }
692801
public CompletableFuture<Void> close() {
    CompletableFuture<Void> future = new CompletableFuture<>();
    submitter.close()
      .thenCompose(v -> listener.close())
      .thenCompose(v -> manager.close())
      .whenComplete((managerResult, managerError) -> {
        connection.close().whenComplete((connectionResult, connectionError) -> {
          if (managerError != null) {
            future.completeExceptionally(managerError);
          } else if (connectionError != null) {
            future.completeExceptionally(connectionError);
          } else {
            future.complete(null);
          }
        });
      });
    return future;
  }
24784
public void stop() {

    reflector.stop();
    reflectorFuture.cancel(true);
    reflectExecutor.shutdown();

    if (resyncFuture != null) {
      resyncFuture.cancel(true);
      resyncExecutor.shutdown();
    }
  }
1326689
public ListenableFuture<?> closeAndDelete() {

        // We're going away, so shut ourselves from the external world
        m_closed = true;
        m_ackMailboxRefs.set(null);

        // Export mastership should have been released: force it.
        m_mastershipAccepted.set(false);

        // FIXME: necessary? Old processor should have been shut down.
        // Returning null indicates end of stream
        try {
            if (m_pollTask != null) {
                m_pollTask.setFuture(null);
            }
        } catch (RejectedExecutionException reex) {
            // Ignore, {@code GuestProcessor} was closed
        }
        m_pollTask = null;

        return m_es.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    // Discard the pending container, shortcutting the standard discard logic
                    AckingContainer ack = m_pendingContainer.getAndSet(null);
                    if (ack != null) {
                        if (exportLog.isDebugEnabled()) {
                            exportLog.debug("Discard pending container, lastSeqNo: " + ack.getLastSeqNo());
                        }
                        ack.internalDiscard();
                    }
                    m_committedBuffers.closeAndDelete();
                    m_adFile.delete();
                } catch(IOException e) {
                    exportLog.rateLimitedLog(60, Level.WARN, e, "Error closing commit buffers");
                } finally {
                    m_es.shutdown();
                }
            }
        });
    }
1239522
public CompletableFuture<E> nextEvent() {
    E event = events.poll();
    if (event != null) {
      return CompletableFuture.completedFuture(event);
    } else {
      CompletableFuture<E> future = new CompletableFuture<>();
      futures.add(future);
      return future;
    }
  }
190722
@Override
	public CompletableFuture<Void> onStop() {
		log.info("Stopping the JobMaster for job {}({}).", jobGraph.getName(), jobGraph.getJobID());

		// disconnect from all registered TaskExecutors
		final Set<ResourceID> taskManagerResourceIds = new HashSet<>(registeredTaskManagers.keySet());
		final FlinkException cause = new FlinkException("Stopping JobMaster for job " + jobGraph.getName() +
			'(' + jobGraph.getJobID() + ").");

		for (ResourceID taskManagerResourceId : taskManagerResourceIds) {
			disconnectTaskManager(taskManagerResourceId, cause);
		}

		taskManagerHeartbeatManager.stop();
		resourceManagerHeartbeatManager.stop();

		// make sure there is a graceful exit
		suspendExecution(new FlinkException("JobManager is shutting down."));

		// shut down will internally release all registered slots
		slotPool.close();

		return CompletableFuture.completedFuture(null);
	}
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);
        }
    }
1031793
public static Schedulers stopAll() {
        createSingleton();
        if (instance.runningSchedullers.isEmpty()) {
            throw new IllegalStateException("No schedulers available.");
        }

        for (Entry<String, ScheduledFuture<?>> entry : instance.runningSchedullers.entrySet()) {
            ScheduledFuture<?> future = entry.getValue();
            future.cancel(true);
            Schedulers.decreaseNoOfSchedullers();
            Schedulers.decreaseNoOfRunningSchedullers();
        }

        return instance;
    }
98333
public ServiceBroker stop() {

		// Stop internal components
		stop(transporter);
		stop(serviceRegistry);
		stop(eventbus);
		stop(serviceInvoker);
		stop(contextFactory);
		stop(strategyFactory);
		stop(uidGenerator);

		// Shutdown thread pools
		if (config.isShutDownThreadPools()) {
			ExecutorService executor = config.getExecutor();
			if (executor != null && !executor.isShutdown() && !executor.isTerminated()) {
				try {
					executor.shutdownNow();
				} catch (Exception ignored) {
				}
			}
			logger.info("Task Executor Service stopped.");
			ScheduledExecutorService scheduler = config.getScheduler();
			if (scheduler != null && !scheduler.isShutdown() && !scheduler.isTerminated()) {
				try {
					scheduler.shutdownNow();
				} catch (Exception ignored) {
				}
			}
			logger.info("Task Scheduler Service stopped.");
		}
		return this;
	}
71945
@Override
    public void shutdown() {
        final WireMockServer server = this;
        Thread shutdownThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // We have to sleep briefly to finish serving the shutdown request before stopping the server, as
                    // there's no support in Jetty for shutting down after the current request.
                    // See http://stackoverflow.com/questions/4650713
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                server.stop();
            }
        });
        shutdownThread.start();
    }
343654
public Future<Void> close() {
        return this.allChannels.close().addListener(new GenericFutureListener<Future<Void>>() {
            @Override
            public void operationComplete(final Future<Void> future) throws Exception {
                ApnsChannelPool.this.isClosed = true;

                if (ApnsChannelPool.this.channelFactory instanceof Closeable) {
                    ((Closeable) ApnsChannelPool.this.channelFactory).close();
                }

                for (final Promise<Channel> acquisitionPromise : ApnsChannelPool.this.pendingAcquisitionPromises) {
                    acquisitionPromise.tryFailure(POOL_CLOSED_EXCEPTION);
                }
            }
        });
    }