List of usage examples for java.util.concurrent ThreadPoolExecutor shutdownNow
public List<Runnable> shutdownNow()
From source file:org.geoserver.GeoserverInitStartupListener.java
/** * This method tries hard to stop all threads and remove all references to classes in GeoServer * so that we can avoid permgen leaks on application undeploy. * What happes is that, if any JDK class references to one of the classes loaded by the * webapp classloader, then the classloader cannot be collected and neither can all the * classes loaded by it (since each class keeps a back reference to the classloader that * loaded it). The same happens for any residual thread launched by the web app. *///w w w.j a v a 2 s .co m public void contextDestroyed(ServletContextEvent sce) { try { LOGGER.info("Beginning GeoServer cleanup sequence"); // the dreaded classloader ClassLoader webappClassLoader = getClass().getClassLoader(); // unload all of the jdbc drivers we have loaded. We need to store them and unregister // later to avoid concurrent modification exceptions Enumeration<Driver> drivers = DriverManager.getDrivers(); Set<Driver> driversToUnload = new HashSet<Driver>(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); try { // the driver class loader can be null if the driver comes from the JDK, such as the // sun.jdbc.odbc.JdbcOdbcDriver ClassLoader driverClassLoader = driver.getClass().getClassLoader(); if (driverClassLoader != null && webappClassLoader.equals(driverClassLoader)) { driversToUnload.add(driver); } } catch (Throwable t) { t.printStackTrace(); } } for (Driver driver : driversToUnload) { try { DriverManager.deregisterDriver(driver); LOGGER.info("Unregistered JDBC driver " + driver); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Could now unload driver " + driver.getClass(), e); } } drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); } try { Class h2Driver = Class.forName("org.h2.Driver"); Method m = h2Driver.getMethod("unload"); m.invoke(null); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to unload the H2 driver", e); } // unload all deferred authority factories so that we get rid of the timer tasks in them try { disposeAuthorityFactories(ReferencingFactoryFinder.getCoordinateOperationAuthorityFactories(null)); } catch (Throwable e) { LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e); } try { disposeAuthorityFactories(ReferencingFactoryFinder.getCRSAuthorityFactories(null)); } catch (Throwable e) { LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e); } try { disposeAuthorityFactories(ReferencingFactoryFinder.getCSAuthorityFactories(null)); } catch (Throwable e) { LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e); } // kill the threads created by referencing WeakCollectionCleaner.DEFAULT.exit(); DeferredAuthorityFactory.exit(); CRS.reset("all"); LOGGER.info("Shut down GT referencing threads "); // reset ReferencingFactoryFinder.reset(); CommonFactoryFinder.reset(); DataStoreFinder.reset(); DataAccessFinder.reset(); LOGGER.info("Shut down GT SPI "); LOGGER.info("Shut down coverage thread pool "); Object o = Hints.getSystemDefault(Hints.EXECUTOR_SERVICE); if (o != null && o instanceof ExecutorService) { final ThreadPoolExecutor executor = (ThreadPoolExecutor) o; try { executor.shutdown(); } finally { try { executor.shutdownNow(); } finally { } } } // unload everything that JAI ImageIO can still refer to // We need to store them and unregister later to avoid concurrent modification exceptions final IIORegistry ioRegistry = IIORegistry.getDefaultInstance(); Set<IIOServiceProvider> providersToUnload = new HashSet(); for (Iterator<Class<?>> cats = ioRegistry.getCategories(); cats.hasNext();) { Class<?> category = cats.next(); for (Iterator it = ioRegistry.getServiceProviders(category, false); it.hasNext();) { final IIOServiceProvider provider = (IIOServiceProvider) it.next(); if (webappClassLoader.equals(provider.getClass().getClassLoader())) { providersToUnload.add(provider); } } } for (IIOServiceProvider provider : providersToUnload) { ioRegistry.deregisterServiceProvider(provider); LOGGER.info("Unregistering Image I/O provider " + provider); } // unload everything that JAI can still refer to final OperationRegistry opRegistry = JAI.getDefaultInstance().getOperationRegistry(); for (String mode : RegistryMode.getModeNames()) { for (Iterator descriptors = opRegistry.getDescriptors(mode).iterator(); descriptors != null && descriptors.hasNext();) { RegistryElementDescriptor red = (RegistryElementDescriptor) descriptors.next(); int factoryCount = 0; int unregisteredCount = 0; // look for all the factories for that operation for (Iterator factories = opRegistry.getFactoryIterator(mode, red.getName()); factories != null && factories.hasNext();) { Object factory = factories.next(); if (factory == null) { continue; } factoryCount++; if (webappClassLoader.equals(factory.getClass().getClassLoader())) { boolean unregistered = false; // we need to scan against all "products" to unregister the factory Vector orderedProductList = opRegistry.getOrderedProductList(mode, red.getName()); if (orderedProductList != null) { for (Iterator products = orderedProductList.iterator(); products != null && products.hasNext();) { String product = (String) products.next(); try { opRegistry.unregisterFactory(mode, red.getName(), product, factory); LOGGER.info("Unregistering JAI factory " + factory.getClass()); } catch (Throwable t) { // may fail due to the factory not being registered against that product } } } if (unregistered) { unregisteredCount++; } } } // if all the factories were unregistered, get rid of the descriptor as well if (factoryCount > 0 && unregisteredCount == factoryCount) { opRegistry.unregisterDescriptor(red); } } } // flush all javabean introspection caches as this too can keep a webapp classloader from being unloaded Introspector.flushCaches(); LOGGER.info("Cleaned up javabean caches"); // unload the logging framework if (!relinquishLoggingControl) LogManager.shutdown(); LogFactory.release(Thread.currentThread().getContextClassLoader()); // GeoTools/GeoServer have a lot of finalizers and until they are run the JVM // itself wil keepup the class loader... try { System.gc(); System.runFinalization(); System.gc(); System.runFinalization(); System.gc(); System.runFinalization(); } catch (Throwable t) { System.out.println("Failed to perform closing up finalization"); t.printStackTrace(); } } catch (Throwable t) { // if anything goes south during the cleanup procedures I want to know what it is t.printStackTrace(); } }
From source file:org.hyperic.hq.measurement.agent.server.ScheduleThread.java
/** * Shut down the schedule thread.// ww w . j ava 2 s . c om */ void die() { shouldDie.set(true); for (String s : executors.keySet()) { ThreadPoolExecutor executor = executors.get(s); List<Runnable> queuedMetrics = executor.shutdownNow(); log.info("Shut down executor service for plugin '" + s + "'" + " with " + queuedMetrics.size() + " queued collections"); } metricLoggingTask.cancel(true); metricVerificationTask.cancel(true); List<Runnable> pending = metricVerificationService.shutdownNow(); log.info("Shutdown metric verification task with " + pending.size() + " tasks"); interruptMe(); }
From source file:org.yccheok.jstock.engine.StockHistoryMonitor.java
public void clearStockCodes() { writerLock.lock();/*from ww w . j av a2 s .c om*/ try { final ThreadPoolExecutor threadPoolExecutor = ((ThreadPoolExecutor) pool); final int nThreads = threadPoolExecutor.getMaximumPoolSize(); stockCodes.clear(); histories.clear(); threadPoolExecutor.shutdownNow(); // pool is not valid any more. Discard it and re-create. pool = Executors.newFixedThreadPool(nThreads); } finally { writerLock.unlock(); } }
From source file:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java
/** * Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads() *//*from w ww .j a v a 2 s . c o m*/ @SuppressWarnings("deprecation") protected void stopThreads() { final Class<?> workerClass = findClass("java.util.concurrent.ThreadPoolExecutor$Worker"); final Field oracleTarget = findField(Thread.class, "target"); // Sun/Oracle JRE final Field ibmRunnable = findField(Thread.class, "runnable"); // IBM JRE for (Thread thread : getAllThreads()) { final Runnable runnable = (oracleTarget != null) ? (Runnable) getFieldValue(oracleTarget, thread) : // Sun/Oracle JRE (Runnable) getFieldValue(ibmRunnable, thread); // IBM JRE if (thread != Thread.currentThread() && // Ignore current thread (isThreadInWebApplication(thread) || isLoadedInWebApplication(runnable))) { if (thread.getClass().getName().startsWith(JURT_ASYNCHRONOUS_FINALIZER)) { // Note, the thread group of this thread may be "system" if it is triggered by the Garbage Collector // however if triggered by us in forceStartOpenOfficeJurtCleanup() it may depend on the application server if (stopThreads) { info("Found JURT thread " + thread.getName() + "; starting " + JURTKiller.class.getSimpleName()); new JURTKiller(thread).start(); } else warn("JURT thread " + thread.getName() + " is still running in web app"); } else if (thread.getThreadGroup() != null && ("system".equals(thread.getThreadGroup().getName()) || // System thread "RMI Runtime".equals(thread.getThreadGroup().getName()))) { // RMI thread (honestly, just copied from Tomcat) if ("Keep-Alive-Timer".equals(thread.getName())) { thread.setContextClassLoader(getWebApplicationClassLoader().getParent()); debug("Changed contextClassLoader of HTTP keep alive thread"); } } else if (thread.isAlive()) { // Non-system, running in web app if ("java.util.TimerThread".equals(thread.getClass().getName())) { if (stopTimerThreads) { warn("Stopping Timer thread running in classloader."); stopTimerThread(thread); } else { info("Timer thread is running in classloader, but will not be stopped"); } } else { // If threads is running an java.util.concurrent.ThreadPoolExecutor.Worker try shutting down the executor if (workerClass != null && workerClass.isInstance(runnable)) { if (stopThreads) { warn("Shutting down " + ThreadPoolExecutor.class.getName() + " running within the classloader."); try { // java.util.concurrent.ThreadPoolExecutor, introduced in Java 1.5 final Field workerExecutor = findField(workerClass, "this$0"); final ThreadPoolExecutor executor = getFieldValue(workerExecutor, runnable); executor.shutdownNow(); } catch (Exception ex) { error(ex); } } else info(ThreadPoolExecutor.class.getName() + " running within the classloader will not be shut down."); } final String displayString = "'" + thread + "' of type " + thread.getClass().getName(); if (stopThreads) { final String waitString = (threadWaitMs > 0) ? "after " + threadWaitMs + " ms " : ""; warn("Stopping Thread " + displayString + " running in web app " + waitString); if (threadWaitMs > 0) { try { thread.join(threadWaitMs); // Wait for thread to run } catch (InterruptedException e) { // Do nothing } } // Normally threads should not be stopped (method is deprecated), since it may cause an inconsistent state. // In this case however, the alternative is a classloader leak, which may or may not be considered worse. if (thread.isAlive()) thread.stop(); } else { warn("Thread " + displayString + " is still running in web app"); } } } } } }