    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 *      http://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.beanutils2;
    019
    020import java.util.Map;
    021import java.util.WeakHashMap;
    022
    023/**
    024 * An instance of this class represents a value that is provided per (thread) context classloader.
    025 *
    026 * <p>
    027 * Occasionally it is necessary to store data in "global" variables (including uses of the Singleton pattern). In applications which have only a single
    028 * classloader such data can simply be stored as "static" members on some class. When multiple class loaders are involved, however, this approach can fail; in
    029 * particular, this doesn't work when the code may be run within a servlet container or a j2ee container, and the class on which the static member is defined is
    030 * loaded via a "shared" classloader that is visible to all components running within the container. This class provides a mechanism for associating data with a
    031 * ClassLoader instance, which ensures that when the code runs in such a container each component gets its own copy of the "global" variable rather than
    032 * unexpectedly sharing a single copy of the variable with other components that happen to be running in the same container at the same time (eg servlets or
    033 * EJBs.)
    034 * </p>
    035 *
    036 * <p>
    037 * This class is strongly patterned after the java.lang.ThreadLocal class, which performs a similar task in allowing data to be associated with a particular
    038 * thread.
    039 * </p>
    040 *
    041 * <p>
    042 * When code that uses this class is run as a "normal" application, ie not within a container, the effect is identical to just using a static member variable to
    043 * store the data, because Thread.getContextClassLoader always returns the same classloader (the system classloader).
    044 * </p>
    045 *
    046 * <p>
    047 * Expected usage is as follows:
    048 * </p>
    049 *
    050 * <pre>
    051 * <code>
    052 *  public class SomeClass {
    053 *    private static final ContextClassLoaderLocal&lt;String&gt; global
    054 *      = new ContextClassLoaderLocal&lt;String&gt;() {
    055 *          protected String initialValue() {
    056 *              return new String("Initial value");
    057 *          };
    058 *
    059 *    public void testGlobal() {
    060 *      String s = global.get();
    061 *      System.out.println("global value:" + s);
    062 *      buf.set("New Value");
    063 *    }
    064 * </code>
    065 * </pre>
    066 *
    067 * <p>
    068 * <strong>Note:</strong> This class takes some care to ensure that when a component which uses this class is "undeployed" by a container the component-specific
    069 * classloader and all its associated classes (and their static variables) are garbage-collected. Unfortunately there is one scenario in which this does
    070 * <em>not</em> work correctly and there is unfortunately no known workaround other than ensuring that the component (or its container) calls the "unset" method
    071 * on this class for each instance of this class when the component is undeployed. The problem occurs if:
    072 * <ul>
    073 * <li>the class containing a static instance of this class was loaded via a shared classloader, and</li>
    074 * <li>the value stored in the instance is an object whose class was loaded via the component-specific classloader (or any of the objects it refers to were
    075 * loaded via that classloader).</li>
    076 * </ul>
    077 * <p>
    078 * The result is that the map managed by this object still contains a strong reference to the stored object, which contains a strong reference to the
    079 * classloader that loaded it, meaning that although the container has "undeployed" the component the component-specific classloader and all the related classes
    080 * and static variables cannot be garbage-collected. This is not expected to be an issue with the commons-beanutils library as the only classes which use this
    081 * class are BeanUtilsBean and ConvertUtilsBean and there is no obvious reason for a user of the BeanUtils library to subclass either of those classes.
    082 * </p>
    083 *
    084 * <p>
    085 * <strong>Note:</strong> A WeakHashMap bug in several 1.3 JVMs results in a memory leak for those JVMs.
    086 * </p>
    087 *
    088 * <p>
    089 * <strong>Note:</strong> Of course, all of this would be unnecessary if containers required each component to load the full set of classes it needs, that is,
    090 * avoided providing classes loaded via a "shared" classloader.
    091 * </p>
    092 *
    093 * @param <T> the type of data stored in an instance
    094 * @see Thread#getContextClassLoader
    095 */
    096public class ContextClassLoaderLocal<T> {
    097    private final Map<ClassLoader, T> valueByClassLoader = new WeakHashMap<>();
    098    private boolean globalValueInitialized;
    099    private T globalValue;
    100
    101    /**
    102     * Constructs a context classloader instance
    103     */
    104    public ContextClassLoaderLocal() {
    105    }
    106
    107    /**
    108     * Gets the instance which provides the functionality for {@link BeanUtils}. This is a pseudo-singleton - an single instance is provided per (thread)
    109     * context classloader. This mechanism provides isolation for web apps deployed in the same container.
    110     *
    111     * @return the object currently associated with the context-classloader of the current thread.
    112     */
    113    public synchronized T get() {
    114        // synchronizing the whole method is a bit slower
    115        // but guarantees no subtle threading problems, and there's no
    116        // need to synchronize valueByClassLoader
    117
    118        // make sure that the map is given a change to purge itself
    119        valueByClassLoader.isEmpty();
    120        try {
    121
    122            final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    123            if (contextClassLoader != null) {
    124
    125                T value = valueByClassLoader.get(contextClassLoader);
    126                if (value == null && !valueByClassLoader.containsKey(contextClassLoader)) {
    127                    value = initialValue();
    128                    valueByClassLoader.put(contextClassLoader, value);
    129                }
    130                return value;
    131
    132            }
    133
    134        } catch (final SecurityException e) {
    135            /* SWALLOW - should we log this? */ }
    136
    137        // if none or exception, return the globalValue
    138        if (!globalValueInitialized) {
    139            globalValue = initialValue();
    140            globalValueInitialized = true;
    141        } // else already set
    142        return globalValue;
    143    }
    144
    145    /**
    146     * Returns the initial value for this ContextClassLoaderLocal variable. This method will be called once per Context ClassLoader for each
    147     * ContextClassLoaderLocal, the first time it is accessed with get or set. If the programmer desires ContextClassLoaderLocal variables to be initialized to
    148     * some value other than null, ContextClassLoaderLocal must be subclassed, and this method overridden. Typically, an anonymous inner class will be used.
    149     * Typical implementations of initialValue will call an appropriate constructor and return the newly constructed object.
    150     *
    151     * @return a new Object to be used as an initial value for this ContextClassLoaderLocal
    152     */
    153    protected T initialValue() {
    154        return null;
    155    }
    156
    157    /**
    158     * Sets the value - a value is provided per (thread) context classloader. This mechanism provides isolation for web apps deployed in the same container.
    159     *
    160     * @param value the object to be associated with the entrant thread's context classloader
    161     */
    162    public synchronized void set(final T value) {
    163        // synchronizing the whole method is a bit slower
    164        // but guarantees no subtle threading problems
    165
    166        // make sure that the map is given a change to purge itself
    167        valueByClassLoader.isEmpty();
    168        try {
    169
    170            final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    171            if (contextClassLoader != null) {
    172                valueByClassLoader.put(contextClassLoader, value);
    173                return;
    174            }
    175
    176        } catch (final SecurityException e) {
    177            /* SWALLOW - should we log this? */ }
    178
    179        // if in doubt, set the global value
    180        globalValue = value;
    181        globalValueInitialized = true;
    182    }
    183
    184    /**
    185     * Unsets the value associated with the current thread's context classloader
    186     */
    187    public synchronized void unset() {
    188        try {
    189
    190            final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    191            unset(contextClassLoader);
    192
    193        } catch (final SecurityException e) {
    194            /* SWALLOW - should we log this? */ }
    195    }
    196
    197    /**
    198     * Unsets the value associated with the given classloader
    199     *
    200     * @param classLoader The classloader to <em>unset</em> for
    201     */
    202    public synchronized void unset(final ClassLoader classLoader) {
    203        valueByClassLoader.remove(classLoader);
    204    }
    205}