ContextClassLoaderLocal.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.beanutils2;

  18. import java.util.Map;
  19. import java.util.WeakHashMap;

  20. /**
  21.  * An instance of this class represents a value that is provided per (thread) context classloader.
  22.  *
  23.  * <p>
  24.  * Occasionally it is necessary to store data in "global" variables (including uses of the Singleton pattern). In applications which have only a single
  25.  * 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
  26.  * 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
  27.  * 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
  28.  * 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
  29.  * 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
  30.  * EJBs.)
  31.  * </p>
  32.  *
  33.  * <p>
  34.  * 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
  35.  * thread.
  36.  * </p>
  37.  *
  38.  * <p>
  39.  * 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
  40.  * store the data, because Thread.getContextClassLoader always returns the same classloader (the system classloader).
  41.  * </p>
  42.  *
  43.  * <p>
  44.  * Expected usage is as follows:
  45.  * </p>
  46.  *
  47.  * <pre>
  48.  * <code>
  49.  *  public class SomeClass {
  50.  *    private static final ContextClassLoaderLocal&lt;String&gt; global
  51.  *      = new ContextClassLoaderLocal&lt;String&gt;() {
  52.  *          protected String initialValue() {
  53.  *              return new String("Initial value");
  54.  *          };
  55.  *
  56.  *    public void testGlobal() {
  57.  *      String s = global.get();
  58.  *      System.out.println("global value:" + s);
  59.  *      buf.set("New Value");
  60.  *    }
  61.  * </code>
  62.  * </pre>
  63.  *
  64.  * <p>
  65.  * <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
  66.  * classloader and all its associated classes (and their static variables) are garbage-collected. Unfortunately there is one scenario in which this does
  67.  * <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
  68.  * on this class for each instance of this class when the component is undeployed. The problem occurs if:
  69.  * <ul>
  70.  * <li>the class containing a static instance of this class was loaded via a shared classloader, and</li>
  71.  * <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
  72.  * loaded via that classloader).</li>
  73.  * </ul>
  74.  * <p>
  75.  * 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
  76.  * classloader that loaded it, meaning that although the container has "undeployed" the component the component-specific classloader and all the related classes
  77.  * 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
  78.  * class are BeanUtilsBean and ConvertUtilsBean and there is no obvious reason for a user of the BeanUtils library to subclass either of those classes.
  79.  * </p>
  80.  *
  81.  * <p>
  82.  * <strong>Note:</strong> A WeakHashMap bug in several 1.3 JVMs results in a memory leak for those JVMs.
  83.  * </p>
  84.  *
  85.  * <p>
  86.  * <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,
  87.  * avoided providing classes loaded via a "shared" classloader.
  88.  * </p>
  89.  *
  90.  * @param <T> the type of data stored in an instance
  91.  * @see Thread#getContextClassLoader
  92.  */
  93. public class ContextClassLoaderLocal<T> {
  94.     private final Map<ClassLoader, T> valueByClassLoader = new WeakHashMap<>();
  95.     private boolean globalValueInitialized;
  96.     private T globalValue;

  97.     /**
  98.      * Constructs a context classloader instance
  99.      */
  100.     public ContextClassLoaderLocal() {
  101.     }

  102.     /**
  103.      * Gets the instance which provides the functionality for {@link BeanUtils}. This is a pseudo-singleton - an single instance is provided per (thread)
  104.      * context classloader. This mechanism provides isolation for web apps deployed in the same container.
  105.      *
  106.      * @return the object currently associated with the context-classloader of the current thread.
  107.      */
  108.     public synchronized T get() {
  109.         // synchronizing the whole method is a bit slower
  110.         // but guarantees no subtle threading problems, and there's no
  111.         // need to synchronize valueByClassLoader

  112.         // make sure that the map is given a change to purge itself
  113.         valueByClassLoader.isEmpty();
  114.         try {

  115.             final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
  116.             if (contextClassLoader != null) {

  117.                 T value = valueByClassLoader.get(contextClassLoader);
  118.                 if (value == null && !valueByClassLoader.containsKey(contextClassLoader)) {
  119.                     value = initialValue();
  120.                     valueByClassLoader.put(contextClassLoader, value);
  121.                 }
  122.                 return value;

  123.             }

  124.         } catch (final SecurityException e) {
  125.             /* SWALLOW - should we log this? */ }

  126.         // if none or exception, return the globalValue
  127.         if (!globalValueInitialized) {
  128.             globalValue = initialValue();
  129.             globalValueInitialized = true;
  130.         } // else already set
  131.         return globalValue;
  132.     }

  133.     /**
  134.      * Returns the initial value for this ContextClassLoaderLocal variable. This method will be called once per Context ClassLoader for each
  135.      * ContextClassLoaderLocal, the first time it is accessed with get or set. If the programmer desires ContextClassLoaderLocal variables to be initialized to
  136.      * some value other than null, ContextClassLoaderLocal must be subclassed, and this method overridden. Typically, an anonymous inner class will be used.
  137.      * Typical implementations of initialValue will call an appropriate constructor and return the newly constructed object.
  138.      *
  139.      * @return a new Object to be used as an initial value for this ContextClassLoaderLocal
  140.      */
  141.     protected T initialValue() {
  142.         return null;
  143.     }

  144.     /**
  145.      * Sets the value - a value is provided per (thread) context classloader. This mechanism provides isolation for web apps deployed in the same container.
  146.      *
  147.      * @param value the object to be associated with the entrant thread's context classloader
  148.      */
  149.     public synchronized void set(final T value) {
  150.         // synchronizing the whole method is a bit slower
  151.         // but guarantees no subtle threading problems

  152.         // make sure that the map is given a change to purge itself
  153.         valueByClassLoader.isEmpty();
  154.         try {

  155.             final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
  156.             if (contextClassLoader != null) {
  157.                 valueByClassLoader.put(contextClassLoader, value);
  158.                 return;
  159.             }

  160.         } catch (final SecurityException e) {
  161.             /* SWALLOW - should we log this? */ }

  162.         // if in doubt, set the global value
  163.         globalValue = value;
  164.         globalValueInitialized = true;
  165.     }

  166.     /**
  167.      * Unsets the value associated with the current thread's context classloader
  168.      */
  169.     public synchronized void unset() {
  170.         try {

  171.             final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
  172.             unset(contextClassLoader);

  173.         } catch (final SecurityException e) {
  174.             /* SWALLOW - should we log this? */ }
  175.     }

  176.     /**
  177.      * Unsets the value associated with the given classloader
  178.      *
  179.      * @param classLoader The classloader to <em>unset</em> for
  180.      */
  181.     public synchronized void unset(final ClassLoader classLoader) {
  182.         valueByClassLoader.remove(classLoader);
  183.     }
  184. }