1
2
3
4
5
6 package org.backsource.utils.lang;
7
8 import java.util.Map;
9 import java.util.Collections;
10 import java.util.WeakHashMap;
11 /***
12 * <p>The classloader equivalent of ThreadLocal.
13 * </p>
14 *
15 * <p>This class provides class context variable. This means that it
16 * is possible to get a static variable to only be visable in the
17 * context class loader, which is verry usefull to get Singleton
18 * behaviour without the static variable beeing propagated to the
19 * complete JVM.</p>
20 *
21 * <p>It is modelled after the ThreadLocal class, and the same
22 * limitations is valid: only threads executing in the same context
23 * classloader that set a value will be able to se the value. See
24 * {@link InheritableClassContextLocal} and {@link FindClassContextLocal} for other cinds of behaviour.</p>
25 *
26 * <p>Example. You want a singleton, but it must only be valid (set)
27 * in a single component, but you can not guarantee that the singleton
28 * class will not be loaded i a parent (global) classloader.</p>
29 *
30 * <p>If you however know that at least your component will be
31 * executing in its own context classloader you may use this class,
32 * much like using a ThreadLocal.</p>
33 *
34 * <p>Just a demo, set singleton up. Will onlye be available in
35 * current context classloader, even thoug the instance variable is
36 * static</p>
37 *
38 * <pre>
39 * class MySingleton {
40 * static ClassContextLocal instance = new ClassContextLocal();
41 *
42 *
43 * public static void configure(Properties prop) {
44 * MySingleton s = new MySingleton();
45 * s.configure(prop);
46 * instance.set(s);
47 * }
48 *
49 * public static MySingleton getInstance() {
50 * return instance.get();
51 * }
52 *
53 * protected MySingleton() {
54 *
55 * }
56 *
57 * protected void configure(Properties prop) {
58 * //Configure it here
59 * }
60 *
61 * }
62 * </pre>
63 *
64 * @author Peter Antman
65 * @version $Revision: 1.1.1.1 $
66 */
67
68 public class ClassContextLocal {
69 protected Map map = Collections.synchronizedMap(new WeakHashMap(53));
70
71 public ClassContextLocal() {
72
73 }
74
75 /***
76 * Get value from current context class loader.
77 *
78 * @return Object set in this classloader earlier, or null.
79 */
80 public Object get() {
81 ClassLoader cl = Thread.currentThread().getContextClassLoader();
82 return map.get(cl);
83 }
84 /***
85 * Set value in current context class loader.
86 *
87 * @param object save object in current classloader.
88 */
89 public void set(Object object) {
90 ClassLoader cl = Thread.currentThread().getContextClassLoader();
91 map.put(cl,object);
92 }
93 }
94