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