    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.logging.impl;
    019
    020import java.lang.reflect.InvocationTargetException;
    021import java.lang.reflect.Method;
    022
    023import javax.servlet.ServletContextEvent;
    024import javax.servlet.ServletContextListener;
    025
    026import org.apache.commons.logging.LogFactory;
    027
    028/**
    029 * This class is capable of receiving notifications about the undeployment of
    030 * a webapp, and responds by ensuring that commons-logging releases all
    031 * memory associated with the undeployed webapp.
    032 * <p>
    033 * In general, the WeakHashtable support added in commons-logging release 1.1
    034 * ensures that logging classes do not hold references that prevent an
    035 * undeployed webapp's memory from being garbage-collected even when multiple
    036 * copies of commons-logging are deployed via multiple class loaders (a
    037 * situation that earlier versions had problems with). However there are
    038 * some rare cases where the WeakHashtable approach does not work; in these
    039 * situations specifying this class as a listener for the web application will
    040 * ensure that all references held by commons-logging are fully released.
    041 * </p>
    042 * <p>
    043 * To use this class, configure the webapp deployment descriptor to call
    044 * this class on webapp undeploy; the contextDestroyed method will tell
    045 * every accessible LogFactory class that the entry in its map for the
    046 * current webapp's context class loader should be cleared.
    047 * </p>
    048 *
    049 * @since 1.1
    050 */
    051public class ServletContextCleaner implements ServletContextListener {
    052
    053    private static final Class<?>[] RELEASE_SIGNATURE = { ClassLoader.class };
    054
    055    /**
    056     * Constructs a new instance.
    057     */
    058    public ServletContextCleaner() {
    059        // empty
    060    }
    061
    062    /**
    063     * Invoked when a webapp is undeployed, this tells the LogFactory
    064     * class to release any logging information related to the current
    065     * contextClassloader.
    066     */
    067    @Override
    068    public void contextDestroyed(final ServletContextEvent sce) {
    069        final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    070
    071        final Object[] params = new Object[1];
    072        params[0] = tccl;
    073
    074        // Walk up the tree of class loaders, finding all the available
    075        // LogFactory classes and releasing any objects associated with
    076        // the tccl (ie the webapp).
    077        //
    078        // When there is only one LogFactory in the classpath, and it
    079        // is within the webapp being undeployed then there is no problem;
    080        // garbage collection works fine.
    081        //
    082        // When there are multiple LogFactory classes in the classpath but
    083        // parent-first classloading is used everywhere, this loop is really
    084        // short. The first instance of LogFactory found will
    085        // be the highest in the classpath, and then no more will be found.
    086        // This is ok, as with this setup this will be the only LogFactory
    087        // holding any data associated with the tccl being released.
    088        //
    089        // When there are multiple LogFactory classes in the classpath and
    090        // child-first classloading is used in any class loader, then multiple
    091        // LogFactory instances may hold info about this TCCL; whenever the
    092        // webapp makes a call into a class loaded via an ancestor class loader
    093        // and that class calls LogFactory the tccl gets registered in
    094        // the LogFactory instance that is visible from the ancestor
    095        // class loader. However the concrete logging library it points
    096        // to is expected to have been loaded via the TCCL, so the
    097        // underlying logging lib is only initialized/configured once.
    098        // These references from ancestor LogFactory classes down to
    099        // TCCL class loaders are held via weak references and so should
    100        // be released but there are circumstances where they may not.
    101        // Walking up the class loader ancestry ladder releasing
    102        // the current tccl at each level tree, though, will definitely
    103        // clear any problem references.
    104        ClassLoader loader = tccl;
    105        while (loader != null) {
    106            // Load via the current loader. Note that if the class is not accessible
    107            // via this loader, but is accessible via some ancestor then that class
    108            // will be returned.
    109            try {
    110                @SuppressWarnings("unchecked")
    111                final Class<LogFactory> logFactoryClass = (Class<LogFactory>) loader.loadClass("org.apache.commons.logging.LogFactory");
    112                final Method releaseMethod = logFactoryClass.getMethod("release", RELEASE_SIGNATURE);
    113                releaseMethod.invoke(null, params);
    114                loader = logFactoryClass.getClassLoader().getParent();
    115            } catch (final ClassNotFoundException ex) {
    116                // Neither the current class loader nor any of its ancestors could find
    117                // the LogFactory class, so we can stop now.
    118                loader = null;
    119            } catch (final NoSuchMethodException ex) {
    120                // This is not expected; every version of JCL has this method
    121                System.err.println("LogFactory instance found which does not support release method!");
    122                loader = null;
    123            } catch (final IllegalAccessException ex) {
    124                // This is not expected; every ancestor class should be accessible
    125                System.err.println("LogFactory instance found which is not accessible!");
    126                loader = null;
    127            } catch (final InvocationTargetException ex) {
    128                // This is not expected
    129                System.err.println("LogFactory instance release method failed!");
    130                loader = null;
    131            }
    132        }
    133
    134        // Just to be sure, invoke release on the LogFactory that is visible from
    135        // this ServletContextCleaner class too. This should already have been caught
    136        // by the above loop but just in case...
    137        LogFactory.release(tccl);
    138    }
    139
    140    /**
    141     * Invoked when a webapp is deployed. Nothing needs to be done here.
    142     */
    143    @Override
    144    public void contextInitialized(final ServletContextEvent sce) {
    145        // do nothing
    146    }
    147}