Shutdown embedded Kafka and Zookeeper server instances
162441
public void stop() {
        if (kafkaServer != null) {
            try {
                if (kafkaServer.brokerState().currentState() != (NotRunning.state())) {
                    kafkaServer.shutdown();
                    kafkaServer.awaitShutdown();
                }
            } catch (Exception e) {
                log.warn("Failed to shutdown Kafka embedded server", e);
            }

            try {
                CoreUtils.delete(kafkaServer.config().logDirs());
            } catch (Exception e) {
                log.warn("Failed to remove logs on Kafka embedded server", e);
            }
        }

        if (serverFactory != null) {
            try {
                serverFactory.shutdown();
            } catch (Exception e) {
                log.warn("Failed to shutdown Zookeeper instance", e);
            }
        }
    }
988929
public static void shutdown(String instanceName) {
        HazelcastClientProxy proxy = CLIENTS.remove(instanceName);
        if (proxy == null) {
            return;
        }
        HazelcastClientInstanceImpl client = proxy.client;
        if (client == null) {
            return;
        }
        proxy.client = null;
        try {
            client.shutdown();
        } catch (Throwable ignored) {
            EmptyStatement.ignore(ignored);
        } finally {
            OutOfMemoryErrorDispatcher.deregisterClient(client);
        }
    }
1182000
def _setup_kafka(self):
        
        # close older connections
        if self.consumer is not None:
            self.logger.debug("Closing existing kafka consumer")
            self.consumer.close()
            self.consumer = None
        if self.producer is not None:
            self.logger.debug("Closing existing kafka producer")
            self.producer.flush()
            self.producer.close(timeout=10)
            self.producer = None

        # create new connections
        self._consumer_thread = None
        self.logger.debug("Creating kafka connections")
        self.consumer = self._create_consumer()
        if not self.closed:
            self.logger.debug("Kafka Conumer created")
        self.producer = self._create_producer()
        if not self.closed:
            self.logger.debug("Kafka Producer created")

        if not self.closed:
            self.kafka_connected = True
            self.logger.info("Connected successfully to Kafka")
            self._spawn_kafka_consumer_thread()
458180
protected final Mono<Void> shutdownServer(DisposableServer disposableServer) {
    return Mono.defer(
        () ->
            Optional.ofNullable(disposableServer)
                .map(
                    server -> {
                      server.dispose();
                      return server
                          .onDispose()
                          .doOnError(e -> LOGGER.warn("Failed to close server: " + e))
                          .onErrorResume(e -> Mono.empty());
                    })
                .orElse(Mono.empty()));
  }
68141
def shutdown(self):
        
        if self.lifecycle.is_live:
            self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTTING_DOWN)
            self.near_cache_manager.destroy_all_near_caches()
            self.statistics.shutdown()
            self.partition_service.shutdown()
            self.heartbeat.shutdown()
            self.cluster.shutdown()
            self.reactor.shutdown()
            self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTDOWN)
            self.logger.info("Client shutdown.", extra=self._logger_extras)
1318512
public void shutdown() {
        for (Topic topic : _topics.values()) {
            if (topic.getConsumerConnector() != null) {
                topic.getConsumerConnector().shutdown();
            }
            topic.getStreamExecutorService().shutdownNow();
            try {
                topic.getStreamExecutorService().awaitTermination(60, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                _logger.warn("Stream executor service was interrupted while awaiting termination. This should never happen.");
            }
        }
        _logger.debug("Pushing unflushed messages back to Kafka.");

        Producer producer = new Producer(_configuration);

        for (Map.Entry<String, Topic> entry : _topics.entrySet()) {
            String topicName = entry.getKey();
            Topic topic = entry.getValue();
            List<String> unflushedMessages = new ArrayList<String>();

            if (!topic.getMessages().isEmpty()) {
                topic.getMessages().drainTo(unflushedMessages);
                producer.enqueue(topicName, unflushedMessages);
            }
            _logger.debug("{} messages for topic {} enqueued on Kafka queue", unflushedMessages.size(), topicName);
        }
        producer.shutdown();
    }
297468
def shutdown
      stop
      @listeners.each{|s|
        if @logger.debug?
          addr = s.addr
          @logger.debug("close TCPSocket(#{addr[2]}, #{addr[1]})")
        end
        begin
          s.shutdown
        rescue Errno::ENOTCONN
          # when `Errno::ENOTCONN: Socket is not connected' on some platforms,
          # call #close instead of #shutdown.
          # (ignore @config[:ShutdownSocketWithoutClose])
          s.close
        else
          unless @config[:ShutdownSocketWithoutClose]
            s.close
          end
        end
      }
      @listeners.clear
    end
514066
private void shutdown(String applicationName, ClassLoader classLoader) {
        synchronized (configCache) {
            ConfigWrapper configWrapper = configCache.get(classLoader);
            boolean close = configWrapper.removeApplication(applicationName);
            if (close) {
                close(classLoader);
            }
        }
    }
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());
  }
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());

    }
1223500
protected void close() {
        this.authenticating = false;

        // cancel pending futures
        for (Future future : pendingFutures) {
            future.cancel(false);
            CancellableRunnable runnable = cancellables.get(future);
            if (runnable != null) {
                runnable.cancel();
                cancellables.remove(future);
            }
        }

        // shutdown ScheduledExecutorService. Without shutdown, cause thread leak
        if (remoteRequestExecutor != null && !remoteRequestExecutor.isShutdown()) {
            // Note: Time to wait is set 60 sec because RemoteRequest's socket timeout is set 60 seconds.
            Utils.shutdownAndAwaitTermination(remoteRequestExecutor,
                    Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN,
                    Replication.DEFAULT_MAX_TIMEOUT_FOR_SHUTDOWN);
        }

        // Close and remove all idle connections in the pool,
        clientFactory.evictAllConnectionsInPool();
    }
287874
@SuppressWarnings("unused")
    public void destroy() {
        // stop all workers
        for (KafkaMsgConsumerWorker worker : topicWorkers.values()) {
            try {
                worker.stopWorker();
            } catch (Exception e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
        topicWorkers.clear();

        // clear all message listeners
        synchronized (topicMsgListeners) {
            topicMsgListeners.clear();
        }

        // close all KafkaConsumer
        for (KafkaConsumer<String, byte[]> consumer : topicConsumers.values()) {
            synchronized (consumer) {
                try {
                    consumer.close();
                } catch (WakeupException e) {
                } catch (Exception e) {
                    LOGGER.warn(e.getMessage(), e);
                }
            }
        }
        topicConsumers.clear();

        if (executorService != null && myOwnExecutorService) {
            try {
                List<Runnable> tasks = executorService.shutdownNow();
            } catch (Exception e) {
                LOGGER.warn(e.getMessage(), e);
            } finally {
                executorService = null;
            }
        }
    }
437003
def close(self):
        
        self.logger.info("Closing Rest Service")
        self.closed = True

        # close threads
        self._close_thread(self._redis_thread, "Redis setup")
        self._close_thread(self._heartbeat_thread, "Heartbeat")
        self._close_thread(self._kafka_thread, "Kafka setup")
        self._close_thread(self._consumer_thread, "Consumer")

        # close kafka
        if self.consumer is not None:
            self.logger.debug("Closing kafka consumer")
            self.consumer.close()
        if self.producer is not None:
            self.logger.debug("Closing kafka producer")
            self.producer.close(timeout=10)
251788
public void notifyShutdown() {
        if (m_shutdown.compareAndSet(false, true)) {
            for (KafkaExternalConsumerRunner consumer : m_consumers) {
                consumer.shutdown();
            }
            close();
        }
    }
1275329
public void shutdown() {
		running = false;

		// wake up all blocking calls on the queue
		unassignedPartitionsQueue.close();

		// We cannot call close() on the KafkaConsumer, because it will actually throw
		// an exception if a concurrent call is in progress

		// this wakes up the consumer if it is blocked handing over records
		handover.wakeupProducer();

		// this wakes up the consumer if it is blocked in a kafka poll
		synchronized (consumerReassignmentLock) {
			if (consumer != null) {
				consumer.wakeup();
			} else {
				// the consumer is currently isolated for partition reassignment;
				// set this flag so that the wakeup state is restored once the reassignment is complete
				hasBufferedWakeup = true;
			}
		}
	}
1352050
public void shutdown() {
    if (this.shuttingDown.getAndSet(true)) {
      // Already being shut down
      LOG.warn("DataNode.shutdown() was called while shutting down.");
      return;
    }
    if (infoServer != null) {
      try {
        infoServer.stop();
      } catch (Exception e) {
        LOG.warn("Exception shutting down DataNode", e);
      }
    }
    if (ipcServer != null) {
      ipcServer.stop();
    }
    this.shouldRun = false;
    if (dataXceiverServer != null) {
      ((DataXceiverServer) this.dataXceiverServer.getRunnable()).kill();
      this.dataXceiverServer.interrupt();

      // wait for all data receiver threads to exit
      if (this.threadGroup != null) {
        int retries = 0;
        while (true) {
          this.threadGroup.interrupt();
          LOG.info("Waiting for threadgroup to exit, active threads is " +
                   this.threadGroup.activeCount());
          if (this.threadGroup.activeCount() == 0) {
            break;
          }
          try {
            if (++retries > 600) {
              Thread[] activeThreads = new Thread[this.threadGroup.activeCount()];
              this.threadGroup.enumerate(activeThreads, true);
              LOG.info("Active Threads: " + Arrays.toString(activeThreads));
              LOG.warn("Waited for ThreadGroup to be empty for 10 minutes." + 
                        " SHUTTING DOWN NOW");
              break;
            }
            Thread.sleep(1000);
          } catch (InterruptedException e) {}
        }
      }
      // wait for dataXceiveServer to terminate
      try {
        this.dataXceiverServer.join();
      } catch (InterruptedException ie) {
      }
    }
    
    if (blockCopyExecutor != null && !blockCopyExecutor.isShutdown()) {
      blockCopyExecutor.shutdownNow();
    }
    
    if (namespaceManager != null) {
      namespaceManager.shutDownAll();
    }
    
    if (blockScanner != null) { 
      blockScanner.shutdown();
    }
    if(directoryScanner != null) {
      shutdownDirectoryScanner();
    }
    if (storage != null) {
      try {
        this.storage.unlockAll();
      } catch (IOException ie) {
      }
    }
    if (data != null) {
      data.shutdown();
    }
    if (myMetrics != null) {
      setCountingLoggers(null);
      myMetrics.shutdown();
    }
    this.shutdownMXBean();
  }
679245
protected void teardown() throws Exception {
    logger.fine("shutting down channels");
    for (ManagedChannel channel : channels) {
      channel.shutdown();
    }
    logger.fine("shutting down server");
    server.shutdown();
    if (!server.awaitTermination(5, TimeUnit.SECONDS)) {
      logger.warning("Failed to shutdown server");
    }
    logger.fine("server shut down");
    for (ManagedChannel channel : channels) {
      if (!channel.awaitTermination(1, TimeUnit.SECONDS)) {
        logger.warning("Failed to shutdown client");
      }
    }
    logger.fine("channels shut down");
  }