Attach a shutdown hook to make sure that the thread waiting for
the start level to change is posted if the JVM is shut down
493896
@FFDCIgnore({ InterruptedException.class })
    public synchronized void waitForComplete() {
        // Don't bother waiting if the vm has been shutdown in the meanwhile...
        while (done.get() == false && !shutdownHook.vmShutdown()) {
            try {
                // refresh packages should not take a long time..
                wait(1000);
            } catch (InterruptedException e) {
                /** No-op **/
            }
        }
    }
800041
private void removeShutdownHook() {
    if (added && !running) {
      boolean removed = Runtime.getRuntime().removeShutdownHook(
          destroyProcessThread);
      if (!removed) {
        log.error("Could not remove shutdown hook");
      }
      /*
       * start the hook thread, a unstarted thread may not be eligible for
       * garbage collection Cf.: http://developer.java.sun.com/developer/
       * bugParade/bugs/4533087.html
       */

      destroyProcessThread.setShouldDestroy(false);
      destroyProcessThread.start();
      // this should return quickly, since it basically is a NO-OP.
      try {
        destroyProcessThread.join(20000);
      }
      catch (InterruptedException ie) {
        // the thread didn't die in time
        // it should not kill any processes unexpectedly
      }
      destroyProcessThread = null;
      added = false;
    }
  }
950196
public void notifyShutdown() {
		// System.out.println(" AtomCache got notify shutdown..");
		if (pdpprovider != null) {
			if (pdpprovider instanceof RemotePDPProvider) {
				RemotePDPProvider remotePDP = (RemotePDPProvider) pdpprovider;
				remotePDP.flushCache();
			}
		}

		// todo: use a SCOP implementation that is backed by SerializableCache
		ScopDatabase scopInstallation = ScopFactory.getSCOP();
		if (scopInstallation != null) {
			if (scopInstallation instanceof CachedRemoteScopInstallation) {
				CachedRemoteScopInstallation cacheScop = (CachedRemoteScopInstallation) scopInstallation;
				cacheScop.flushCache();
			}
		}

	}
851556
private void stop(ShutdownModeAmp mode)
  {
    _shutdownMode = mode;
    
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();

    try {
      thread.setContextClassLoader(_classLoader);

      if (! _lifecycle.toStopping()) {
        return;
      }

      TreeSet<SubSystem> systems
        = new TreeSet<SubSystem>(new StopComparator());

      systems.addAll(_systemMap.values());

      // sort

      for (SubSystem system : systems) {
        try {
          thread.setContextClassLoader(_classLoader);

          if (log.isLoggable(Level.FINEST)) {
            log.finest(system + " stopping");
          }

          system.stop(mode);
        } catch (Throwable e) {
          log.log(Level.WARNING, e.toString(), e);
        }
      }

    } finally {
      _lifecycle.toStop();

      thread.setContextClassLoader(oldLoader);
    }
  }
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();
    }
321629
public void shutdown()
  {
    log.info("Shutting down...");
    isShutdownRequested = true;

    try
    {
      mainThread.join();
    }
    catch (InterruptedException e)
    {
      log.error(
        "Interrupted which waiting on main daemon thread to complete.");
    }
  }
600710
public void shutdown(ShutdownModeAmp mode)
  {
    stop(mode);

    if (! _lifecycle.toDestroy()) {
      return;
    }
    
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();

    try {
      thread.setContextClassLoader(_classLoader);

      TreeSet<SubSystem> systems
        = new TreeSet<SubSystem>(new StopComparator());

      systems.addAll(_systemMap.values());

      _systemMap.clear();

      for (SubSystem system : systems) {
        try {
          system.destroy();
        } catch (Throwable e) {
          log.log(Level.WARNING, e.toString(), e);
        }
      }

      WeakReference<SystemManager> globalRef = _globalSystemRef;

      if (globalRef != null && globalRef.get() == this) {
        _globalSystemRef = null;
      }

      /*
       * destroy
       */

      log.fine(this + " destroyed");

      _classLoader.destroy();
    } finally {
      // DynamicClassLoader.setOldLoader(thread, oldLoader);
      
      thread.setContextClassLoader(oldLoader);

      _classLoader = null;
    }
  }
1056041
void shutdownNow() {
    shutdown = true;
    for (int i = 0; i < clients.length; i++) {
      clients[i].close();
    }
    fixedThreadPool.shutdownNow();
    system.terminate();
  }
930841
protected void shutDown() {

        synchronized (LOCK) {
            if (getRunLevel() > OpenCms.RUNLEVEL_0_OFFLINE) {
                System.err.println(
                    Messages.get().getBundle().key(
                        Messages.LOG_SHUTDOWN_CONSOLE_NOTE_2,
                        getSystemInfo().getVersionNumber(),
                        getSystemInfo().getWebApplicationName()));
                if (CmsLog.INIT.isInfoEnabled()) {
                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
                    CmsLog.INIT.info(
                        Messages.get().getBundle().key(
                            Messages.INIT_SHUTDOWN_START_1,
                            getSystemInfo().getVersionNumber() + " [" + getSystemInfo().getVersionId() + "]"));
                    CmsLog.INIT.info(
                        Messages.get().getBundle().key(Messages.INIT_CURRENT_RUNLEVEL_1, new Integer(getRunLevel())));
                    CmsLog.INIT.info(
                        Messages.get().getBundle().key(
                            Messages.INIT_SHUTDOWN_TIME_1,
                            new Date(System.currentTimeMillis())));
                }

                // take the system offline
                setRunLevel(OpenCms.RUNLEVEL_0_OFFLINE);

                if (LOG.isDebugEnabled()) {
                    // log exception to see which method did call the shutdown
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_SHUTDOWN_TRACE_0), new Exception());
                }

                try {
                    // the first thing we have to do is to wait until the current publish process finishes
                    if (null != m_publishEngine) {
                        m_publishEngine.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_PUBLISH_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    // search manager must be shut down early since there may be background indexing still ongoing
                    if (m_searchManager != null) {
                        m_searchManager.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_SEARCH_MANAGER_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    // remote shell server must be shut down early since there is a background thread ongoing that reloads from the VFS
                    if (m_remoteShellServer != null) {
                        m_remoteShellServer.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_REMOTESHELL_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    // VFS bundle manager must be shut down early since there is a background thread ongoing that reloads from the VFS
                    if (m_vfsBundleManager != null) {
                        m_vfsBundleManager.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_VFSBUNDLE_MANAGER_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    if (m_staticExportManager != null) {
                        m_staticExportManager.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_EXPORT_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    if (m_moduleManager != null) {
                        m_moduleManager.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_MODULE_SHUTDOWN_1, e.getMessage()),
                        e);
                }

                try {
                    if (m_executor != null) {
                        m_executor.shutdownNow();
                        m_executor.awaitTermination(30, TimeUnit.SECONDS);
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_MODULE_SHUTDOWN_1, e.getMessage()),
                        e);
                }

                try {
                    if (m_scheduleManager != null) {
                        m_scheduleManager.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_SCHEDULE_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    if (m_resourceManager != null) {
                        m_resourceManager.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_RESOURCE_SHUTDOWN_1, e.getMessage()),
                        e);
                }

                try {
                    if (m_repositoryManager != null) {
                        m_repositoryManager.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(e.getLocalizedMessage(), e);
                }

                try {
                    // has to be stopped before the security manager, since this thread uses it
                    if (m_threadStore != null) {
                        m_threadStore.shutDown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_THREAD_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    if (m_securityManager != null) {
                        m_securityManager.destroy();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_SECURITY_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    if (m_sessionManager != null) {
                        m_sessionManager.shutdown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_SESSION_MANAGER_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    if (m_memoryMonitor != null) {
                        m_memoryMonitor.shutdown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_MEMORY_MONITOR_SHUTDOWN_1, e.getMessage()),
                        e);
                }
                try {
                    if (m_adeManager != null) {
                        m_adeManager.shutdown();
                    }
                } catch (Throwable e) {
                    CmsLog.INIT.error(
                        Messages.get().getBundle().key(Messages.LOG_ERROR_ADE_MANAGER_SHUTDOWN_1, e.getMessage()),
                        e);
                }

                String runtime = CmsStringUtil.formatRuntime(getSystemInfo().getRuntime());
                if (CmsLog.INIT.isInfoEnabled()) {
                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_OPENCMS_STOPPED_1, runtime));
                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_LINE_0));
                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
                    CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DOT_0));
                }
                System.err.println(Messages.get().getBundle().key(Messages.LOG_CONSOLE_TOTAL_RUNTIME_1, runtime));

            }
            m_instance = null;
        }
    }
1230034
private static boolean waitForServerDown(int port, long timeout) {
    long start = System.currentTimeMillis();
    while (true) {
      try {
        Socket sock = new Socket("localhost", port);
        try {
          OutputStream outstream = sock.getOutputStream();
          outstream.write("stat".getBytes());
          outstream.flush();
        } finally {
          sock.close();
        }
      } catch (IOException e) {
        return true;
      }

      if (System.currentTimeMillis() > start + timeout) {
        break;
      }
      try {
        Thread.sleep(250);
      } catch (InterruptedException e) {
        // ignore
      }
    }
    return false;
  }
553624
synchronized public void shutdown()
    {
        m_shutdown.set(true);
        if (m_isExecutorServiceLocal) {
            try {
                m_es.shutdown();
                m_es.awaitTermination(365, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                repairLog.warn("Unexpected interrupted exception", e);
            }
        }
    }
346739
public void ensureStarted()
        throws MojoExecutionException
    {
        synchronized ( lock )
        {
            if ( started || starting )
            {
                return;
            }
            starting = true;
            started = false;
            finished = false;
            finishing = false;
        }
        Thread worker = new Thread( new Worker(), "FileSystemServer[" + name + "]" );
        worker.setDaemon( true );
        worker.start();
        try
        {
            synchronized ( lock )
            {
                while ( starting && !started && !finished && !finishing )
                {
                    lock.wait();
                }
                if ( problem != null )
                {
                    throw problem;
                }
            }
        }
        catch ( Exception e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }
1208805
void shutdown() throws InterruptedException {
        m_shouldStop = true;
        if (m_thread != null) {
            m_selector.wakeup();
            m_thread.join();
        }
    }
266476
def thread_started(self):
		
		while self.check_events() is False:
			self._polling_iteration()
			self.stop_event().wait(self.polling_timeout())
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();
    }
766109
public void shutdown() {
        buffer.clear();


        if (thread != null)
            thread.interrupt();
        try {
            // Shutdown() should be a synchronous operation since the iterator is reset after shutdown() is
            // called in AsyncLabelAwareIterator.reset().
            if (thread != null)
                thread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
        thread.shutdown();
        buffer.clear();
    }
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
			}
		}
	}