Example usage for java.beans Introspector flushCaches

List of usage examples for java.beans Introspector flushCaches

Introduction

In this page you can find the example usage for java.beans Introspector flushCaches.

Prototype

public static void flushCaches() 

Source Link

Document

Flush all of the Introspector's internal caches.

Usage

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.
 *///from  w ww . j av  a  2s.  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.DataPurgeJob.java

public synchronized void run() {
    try {/*  ww  w  . java2s  .  c  o  m*/
        if (!HAUtil.isMasterNode()) {
            log.warn("Data Purge invoked on the secondary HQ node.  "
                    + "It should not be run if the node is not master.  Not running");
            return;
        }
        compressData();
        Properties conf = null;
        try {
            conf = serverConfigManager.getConfig();
        } catch (Exception e) {
            throw new SystemException(e);
        }
        final long now = System.currentTimeMillis();
        // need to do this because of the Sun JVM bug
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5102804
        Introspector.flushCaches();
        if (conf != null) {
            purge(conf, now);
        }
    } catch (Throwable e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.jiemamy.utils.DisposableUtil.java

/**
 * ????//w ww  .  ja v  a 2s  .  c o  m
 */
public static synchronized void dispose() {
    while (DISPOSABLES.isEmpty() == false) {
        Disposable disposable = DISPOSABLES.removeLast();
        try {
            disposable.dispose();
        } catch (Throwable t) {
            t.printStackTrace(); // must not use Logger.
        }
    }
    DISPOSABLES.clear();
    Introspector.flushCaches();
}

From source file:org.mule.module.launcher.ArtifactArchiveInstaller.java

/**
 * Desintalls an artifact from the mule container installation.
 *
 * It will remove the artifact folder and the anchor file related
 * @param artifactName name of the artifact to be uninstall.
 *//*from  w ww. j  a  va  2s .com*/
public void desinstallArtifact(final String artifactName) {
    try {
        final File artifactDir = new File(artifactParentDir, artifactName);
        FileUtils.deleteDirectory(artifactDir);
        // remove a marker, harmless, but a tidy artifact dir is always better :)
        File marker = getArtifactAnchorFile(artifactName);
        marker.delete();
        Introspector.flushCaches();
    } catch (Throwable t) {
        if (t instanceof DeploymentException) {
            throw ((DeploymentException) t);
        }

        final String msg = String.format("Failed to undeployArtifact artifact [%s]", artifactName);
        throw new DeploymentException(MessageFactory.createStaticMessage(msg), t);
    }
}

From source file:org.mule.module.launcher.DefaultMuleDeployer.java

public void undeploy(Application app) {
    try {/* w w  w  .ja v  a 2s.  co m*/
        tryToStopApp(app);
        tryToDisposeApp(app);

        final File appDir = new File(MuleContainerBootstrapUtils.getMuleAppsDir(), app.getAppName());
        FileUtils.deleteDirectory(appDir);
        // remove a marker, harmless, but a tidy app dir is always better :)
        File marker = new File(MuleContainerBootstrapUtils.getMuleAppsDir(),
                String.format("%s-anchor.txt", app.getAppName()));
        marker.delete();
        Introspector.flushCaches();
    } catch (Throwable t) {
        if (t instanceof DeploymentException) {
            // re-throw as is
            throw ((DeploymentException) t);
        }

        final String msg = String.format("Failed to undeploy application [%s]", app.getAppName());
        throw new DeploymentException(MessageFactory.createStaticMessage(msg), t);
    }
}

From source file:org.mypsycho.beans.PropertyUtilsBean.java

/**
 * Clear any cached property descriptors information for all classes
 * loaded by any class loaders. This is useful in cases where class
 * loaders are thrown away to implement class reloading.
 *//*from w ww . ja  v a 2s  . c  o m*/
public void clearDescriptors() {

    descriptorsCache.clear();
    Introspector.flushCaches();

}

From source file:org.ops4j.gaderian.impl.RegistryInfrastructureImpl.java

/**
 * Invokes {@link ShutdownCoordinator#shutdown()}, then releases the coordinator, modules and
 * variable sources.// w  w w .j  a  v  a  2s  .co m
 */
public synchronized void shutdown() {
    checkShutdown();

    ServiceSerializationHelper.setServiceSerializationSupport(null);

    // Allow service implementations and such to shutdown.

    ShutdownCoordinator coordinatorService = (ShutdownCoordinator) getService("gaderian.ShutdownCoordinator",
            ShutdownCoordinator.class, null);

    coordinatorService.shutdown();

    // TODO: Should this be moved earlier?

    _shutdown = true;

    // Shutdown infrastructure items, such as proxies.

    _shutdownCoordinator.shutdown();

    _servicePoints = null;
    _servicePointsByInterfaceClassName = null;
    _configurationPoints = null;
    _shutdownCoordinator = null;
    _variableSources = null;
    _serviceModelFactories = null;
    _threadEventNotifier = null;
    _serviceTokens = null;

    // It is believed that the cache held by PropertyUtils can affect application shutdown
    // and reload in some servlet containers (such as Tomcat); this should clear that up.

    PropertyUtils.clearCache();

    synchronized (Gaderian.INTROSPECTOR_MUTEX) {
        Introspector.flushCaches();
    }
}

From source file:org.red5.server.war.MainServlet.java

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *///from  w  w w.  j a v a2 s.  c o m
public void contextDestroyed(ServletContextEvent sce) {
    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 {
        // 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 spring
        // get web application context from the servlet context
        ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) servletContext
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
        if (factory.containsSingleton("default.context")) {
            for (String scope : factory.getRegisteredScopeNames()) {
                logger.debug("Registered scope: " + scope);
            }
            for (String singleton : factory.getSingletonNames()) {
                logger.debug("Registered singleton: " + singleton);
                // factory.destroyScopedBean(singleton);
            }
            factory.destroySingletons();
        }
        servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        applicationContext.close();
        // http://jakarta.apache.org/commons/logging/guide.html#Classloader_and_Memory_Management
        // http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak?action=print
        // LogFactory.release(Thread.currentThread().getContextClassLoader());
    } catch (Throwable e) {
        // may get a java.lang.StackOverflowError when shutting appcontext
        // down in jboss
        e.printStackTrace();
    }
}

From source file:org.red5.server.war.WarLoaderServlet.java

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *//*  ww w. j  av  a  2s  .c  o m*/
@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();
        }
    }
}

From source file:org.rhq.core.pc.PluginContainer.java

/**
 * Does things that help the garbage collector clean up the memory.
 * Only call this after the plugin container has been shutdown.
 *///w  ww.  ja va  2  s  .co  m
private void cleanMemory() {
    Introspector.flushCaches();
    LogFactory.releaseAll();

    // for why we need to do this, see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6727821 
    try {
        Configuration.setConfiguration(null);
    } catch (Throwable t) {
    }

    System.gc();
}