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