@Override public void destroy() { super.destroy(); Enumeration<Driver> e = DriverManager.getDrivers(); while (e.hasMoreElements()) { Driver driver = e.nextElement(); try { if (driver.getClass().getClassLoader() == getClass().getClassLoader()) DriverManager.deregisterDriver(driver); } catch (SQLException e1) { LOG.logError("Cannot unload driver: " + driver); } } LogFactory.releaseAll(); LogManager.shutdown(); // SLF4JLogFactory.releaseAll(); // should be the same as the LogFactory.releaseAll call Iterator<Class<?>> i = IIORegistry.getDefaultInstance().getCategories(); while (i.hasNext()) { Class<?> c = i.next(); Iterator<?> k = IIORegistry.getDefaultInstance().getServiceProviders(c, false); while (k.hasNext()) { Object o = k.next(); if (o.getClass().getClassLoader() == getClass().getClassLoader()) { IIORegistry.getDefaultInstance().deregisterServiceProvider(o); LOG.logDebug("Deregistering JAI driver ", o.getClass()); } } } Introspector.flushCaches(); // just clear the configurations for now, it does not hurt CRSConfiguration.DEFINED_CONFIGURATIONS.clear(); }
/* * (non-Javadoc) * * @see * com.absir.bean.config.IBeanFactoryStopping#stopping(com.absir.bean.basis * .BeanFactory) */ @Override public void stopping(BeanFactory beanFactory) { LOGGER.info("stop begin"); stopConnectionProvider(sessionFactory); for (SessionFactoryImpl sessionFactory : sessionFactoryMapName.keySet()) { stopConnectionProvider(sessionFactory); } Environment.setStarted(false); if (!driverShared) { Enumeration<Driver> enumeration = DriverManager.getDrivers(); while (enumeration.hasMoreElements()) { Driver driver = enumeration.nextElement(); try { DriverManager.deregisterDriver(driver); } catch (Exception e) { LOGGER.error("deregisterDriver " + driver, e); } } } if (driverStoppingCommand != null) { for (String stoppingCommand : driverStoppingCommand) { KernelClass.invokeCommandString(stoppingCommand); } driverStoppingCommand = null; } LOGGER.info("stop complete"); }
public void contextDestroyed(ServletContextEvent sce) { // This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory // leaks wrto this class Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); try { DriverManager.deregisterDriver(driver); LOG.info(String.format("deregistering jdbc driver: %s", driver)); } catch (SQLException e) { LOG.warn(String.format("Error deregistering driver %s", driver), e); } } // Try to kill the TOMCAT abandoned connection clean up thread // to prevent it from holding the whole context in memory causing // a leak Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]); for (Thread t : threadArray) { if (t.getName().contains("Abandoned connection cleanup thread")) { synchronized (t) { t.stop(); // don't complain, it works } } } }
@Override void closeConnection(final Connection connection) throws SQLException { if (aggressiveCompact) { CallableStatement statement = null; try { LOCK.writeLock().lock(); final java.util.Date start = new java.util.Date(); LOGGER.trace("beginning shutdown compact"); statement = dbConnection.prepareCall("SHUTDOWN COMPACT"); statement.execute(); LOGGER.trace( "completed shutdown compact in " + TimeDuration.fromCurrent(start).asCompactString()); } catch (SQLException ex) { LOGGER.error("error during shutdown compact: " + ex.getMessage()); } finally { close(statement); LOCK.writeLock().unlock(); } } try { connection.close(); if (driver != null) { DriverManager.deregisterDriver(driver); driver = null; } } catch (Exception e) { LOGGER.error("error during H2 shutdown: " + e.getMessage()); } }
/** * Context destroyed. * * @param sce the sce */ @Override public void contextDestroyed(ServletContextEvent sce) { ConnectionPool connectionPool; connectionPool = ConnectionPool.getInstance(); connectionPool.shutDown(); // ShutDown Abandoned Connection : memory leaks after Tomcat stops try { AbandonedConnectionCleanupThread.shutdown(); LOG.info("Abandoned connection shut down!"); } catch (InterruptedException e) { LOG.warn("SEVERE problem cleaning up: " + e.getMessage()); e.printStackTrace(); } // This manually deregisters JDBC driver, which prevents Tomcat from complaining about memory // leaks this class Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); try { DriverManager.deregisterDriver(driver); LOG.info(String.format("deregistering jdbc driver: %s ", driver)); } catch (SQLException e) { LOG.error(String.format("Error deregistering driver: %s ", driver), e); } } }
/** * Clearing the in-memory configuration parameters, we will receive notification that the servlet * context is about to be shut down */ @Override public void contextDestroyed(ServletContextEvent sce) { synchronized (servletContext) { logger.info("Webapp shutdown"); // XXX Paul: grabbed this from // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go // in hopes that we can clear all the issues with J2EE containers // during shutdown try { ServletContext ctx = sce.getServletContext(); // prepare spring for shutdown Introspector.flushCaches(); // dereg any drivers for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) { Driver driver = (Driver) e.nextElement(); if (driver.getClass().getClassLoader() == getClass().getClassLoader()) { DriverManager.deregisterDriver(driver); } } // shutdown jmx JMXAgent.shutdown(); // shutdown the persistence thread FilePersistenceThread persistenceThread = FilePersistenceThread.getInstance(); if (persistenceThread != null) { persistenceThread.shutdown(); } // shutdown spring Object attr = ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (attr != null) { // get web application context from the servlet context ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) attr; ConfigurableBeanFactory factory = applicationContext.getBeanFactory(); // for (String scope : factory.getRegisteredScopeNames()) { // logger.debug("Registered scope: " + scope); // } try { for (String singleton : factory.getSingletonNames()) { logger.debug("Registered singleton: " + singleton); factory.destroyScopedBean(singleton); } } catch (RuntimeException e) { } factory.destroySingletons(); ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); applicationContext.close(); } getContextLoader().closeWebApplicationContext(ctx); // org.apache.commons.logging.LogFactory.releaseAll(); // org.apache.log4j.LogManager.getLoggerRepository().shutdown(); // org.apache.log4j.LogManager.shutdown(); } catch (Throwable e) { e.printStackTrace(); } } }
/** INTERNAL */ public static synchronized void unload() { try { if (registered) { registered = false; DriverManager.deregisterDriver(INSTANCE); } } catch (SQLException e) { TraceSystem.traceThrowable(e); } }
public static void unloadDrivers() { Enumeration<Driver> drivers = DriverManager.getDrivers(); try { while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); DriverManager.deregisterDriver(driver); } } catch (Exception e) { log.error("Error unloading the JDBC Drivers", e); } }
private static void deregisterDrivers() { Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { log.warn("卸载JDBC驱动失败:" + driver, e); log.warn("Fail to uninstall JDBC driver:" + driver, e, Locale.ENGLISH); } } }
@AfterClass public static void doTeardown() throws Exception { if (driver != null) { try { driver.close(); } finally { PhoenixTestDriver driver = BaseConnectionlessQueryTest.driver; BaseConnectionlessQueryTest.driver = null; DriverManager.deregisterDriver(driver); } } }
public void contextDestroyed(ServletContextEvent event) { try { Introspector.flushCaches(); for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) { Driver driver = (Driver) e.nextElement(); if (driver.getClass().getClassLoader() == getClass().getClassLoader()) { DriverManager.deregisterDriver(driver); LOG.debug("deregistering driver: " + driver.getClass().getName()); } } } catch (Throwable e) { LOG.error("Failled to cleanup ClassLoader for webapp", e); } }
// Close and unregister the driver. protected static boolean destroyDriver(Driver driver) { if (driver != null) { assert (driver instanceof PhoenixTestDriver); PhoenixTestDriver pdriver = (PhoenixTestDriver) driver; try { try { pdriver.close(); return true; } finally { DriverManager.deregisterDriver(driver); } } catch (Exception e) { logger.warn("Unable to close registered driver: " + driver, e); } } return false; }
// We need to deregister an already existing driver in order // to register a new one. We need to create a new one so that // we register the new one with the new Configuration instance. // Otherwise, we get connection errors because the prior one // is no longer associated with the miniCluster. protected static synchronized void destroyDriver() { if (driver != null) { driverRefCount--; if (driverRefCount == 0) { try { try { driver.close(); } finally { try { DriverManager.deregisterDriver(driver); } finally { driver = null; } } } catch (SQLException e) { } } } }
private void deregisterJdbcDrivers() { final Enumeration<Driver> driverEnumeration = DriverManager.getDrivers(); final List<Driver> drivers = new ArrayList<Driver>(); while (driverEnumeration.hasMoreElements()) { drivers.add(driverEnumeration.nextElement()); } for (Driver driver : drivers) { if (driver.getClass().getClassLoader() != getClass().getClassLoader()) { continue; } try { DriverManager.deregisterDriver(driver); deregisterOracleDiagnosabilityMBean(); } catch (Throwable e) { } } }
@Override public void contextDestroyed(ServletContextEvent contextEvent) { // stop polling TimerTask polling.cancel(); // closing Hibernate SessionFactory: HibernateUtil.getSessionFactory().close(); // unregisters JDBC driver Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver d = drivers.nextElement(); try { DriverManager.deregisterDriver(d); } catch (SQLException e) { LOGGER.warning("Error deregistering driver '" + d.getClass().getName() + "'!"); } } }
@Override public void contextDestroyed(ServletContextEvent arg0) { LOGGER.info("Destroying webapp.."); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); ClassLoader driverclassLoader = driver.getClass().getClassLoader(); ClassLoader thisClassLoader = this.getClass().getClassLoader(); if (driverclassLoader != null && thisClassLoader != null && driverclassLoader.equals(thisClassLoader)) { try { LOGGER.info("Deregistering: " + driver); DriverManager.deregisterDriver(driver); } catch (SQLException e) { e.printStackTrace(); } } } }
// 关闭所有连接,撤销驱动程序的注册 public synchronized void release() { // 等待直到最后一个客户程序调用 if (--clients != 0) { return; } Enumeration allPools = pools.elements(); while (allPools.hasMoreElements()) { DBConnectionPool pool = (DBConnectionPool) allPools.nextElement(); pool.release(); } Enumeration allDrivers = drivers.elements(); while (allDrivers.hasMoreElements()) { Driver driver = (Driver) allDrivers.nextElement(); try { DriverManager.deregisterDriver(driver); log("撤销JDBC驱动程序 " + driver.getClass().getName() + "的注册"); } catch (SQLException e) { log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName()); } } }
/** * Deregister the driver by the given class name from DriverManager * * @param className * @return true if deregister the driver successfully * @throws OdaException */ public boolean deregisterDriver(String className) throws OdaException { if (className == null || className.length() == 0) // no driver class; assume class already deregistered return false; if (isDeregistered(className)) { return true; } Driver driver = findDriver(className, null, false, false); if (driver != null) { try { if (logger.isLoggable(Level.FINER)) logger.finer("Registering with DriverManager: wrapped driver for " + className); if (registeredDrivers.containsKey(className)) { DriverManager.deregisterDriver(new WrappedDriver(driver, className)); registeredDrivers.remove(className); } registeredDrivers.put(className, DRIVER_DEREGISTERED); } catch (SQLException e) { // This shouldn't happen logger.log(Level.WARNING, "Failed to deRegister wrapped driver instance.", e); } } return true; }
/** * Clean up resources used by the application when stopped * * @param event */ @Override public void contextDestroyed(ServletContextEvent event) { webApp.deregister(); try { // Remove the database pool DatabaseManager.shutdown(); // Clean out the introspector Introspector.flushCaches(); // Remove any drivers registered by this classloader for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) { Driver driver = (Driver) e.nextElement(); if (driver.getClass().getClassLoader() == getClass().getClassLoader()) { DriverManager.deregisterDriver(driver); } } } catch (RuntimeException e) { log.error("Failed to cleanup ClassLoader for webapp", e); } catch (Exception e) { log.error("Failed to cleanup ClassLoader for webapp", e); } }
public static void destroy() { ComboPooledDataSource tmp = pool; pool = null; try { tmp.resetPoolManager(true); tmp.hardReset(); sleep(50); } catch (Exception e) { } try { tmp.close(); sleep(50); } catch (Exception e) { } Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver next = drivers.nextElement(); try { DriverManager.deregisterDriver(next); } catch (SQLException e) { e.printStackTrace(); } } }
private void deleteProject(String projectId) { if (!projectId.equals("")) { try { Driver driver = new Driver(); DriverManager.registerDriver(driver); Connection connection = DriverManager.getConnection( Config.DB_HOST + Config.DB_NAME, Config.DB_USER, Config.DB_PASS); Statement statement = connection.createStatement(); statement.executeUpdate("DELETE FROM projects WHERE id='" + projectId + "';"); statement.close(); connection.close(); DriverManager.deregisterDriver(driver); } catch (SQLException e) { System.out.println( "ProjectUploader: deleteProject: SQL Exception couldn't execute sql query!"); } (new File( Config.FILESYSTEM_BASE_PATH + Config.PROJECTS_DIRECTORY + projectId + Config.PROJECTS_EXTENTION)) .delete(); (new File( Config.FILESYSTEM_BASE_PATH + Config.PROJECTS_QR_DIRECTORY + projectId + Config.PROJECTS_QR_EXTENTION)) .delete(); (new File( Config.FILESYSTEM_BASE_PATH + Config.PROJECTS_THUMBNAIL_DIRECTORY + projectId + Config.PROJECTS_THUMBNAIL_EXTENTION_ORIG)) .delete(); (new File( Config.FILESYSTEM_BASE_PATH + Config.PROJECTS_THUMBNAIL_DIRECTORY + projectId + Config.PROJECTS_THUMBNAIL_EXTENTION_SMALL)) .delete(); (new File( Config.FILESYSTEM_BASE_PATH + Config.PROJECTS_THUMBNAIL_DIRECTORY + projectId + Config.PROJECTS_THUMBNAIL_EXTENTION_LARGE)) .delete(); CommonFunctions.deleteDir( new File( Config.FILESYSTEM_BASE_PATH + Config.PROJECTS_UNZIPPED_DIRECTORY + projectId + Config.FILESYSTEM_SEPARATOR)); } else { System.out.println( "ProjectUploader: deleteProject: invalid project id:'" + projectId + "' - couldn't delete!"); } }
/** * Stop intercepting requests. * * @throws SQLException */ public void unregister() throws SQLException { this.connection = null; this.mockJDBCAnswer = null; active = false; DriverManager.deregisterDriver(this); }
/** * 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. */ 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) { LOGGER.severe("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(); } }
/** * Disable everything. * * @throws SQLException * @throws SQLException */ public synchronized void disable() throws SQLException { this.connection = null; this.mockJDBCAnswer = null; DriverManager.deregisterDriver(this); }