1 package org.apache.fulcrum.yaafi.framework.tls;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.HashMap;
23 import java.util.Map;
24
25 /**
26 * Implementation of {@link org.apache.fulcrum.yaafi.framework.tls.ThreadLocalStorage}.
27 *
28 * The code was pasted from the Hivemnind container written by
29 * Howard Lewis Ship and Harish Krishnaswamy
30 *
31 * @author <a href="mailto:siegfried.goeschl@it20one.at">Siegfried Goeschl</a>
32 */
33
34 public class ThreadLocalStorageImpl implements ThreadLocalStorage
35 {
36 private static final String INITIALIZED_KEY =
37 "$org.apache.fulcrum.yaafi.framework.tls.ThreadLocalStorageImpl#initialized$";
38
39 private CleanableThreadLocal local = new CleanableThreadLocal();
40
41 private static class CleanableThreadLocal extends ThreadLocal
42 {
43 /**
44 * <p>
45 * Intializes the variable with a HashMap containing a single Boolean flag to denote the
46 * initialization of the variable.
47 */
48 protected Object initialValue()
49 {
50
51
52
53
54
55
56 Map map = new HashMap();
57 map.put(INITIALIZED_KEY, Boolean.TRUE);
58
59 return map;
60 }
61 }
62
63 /**
64 * Gets the thread local variable and registers the listener with ThreadEventNotifier
65 * if the thread local variable has been initialized. The registration cannot be done from
66 * within {@link CleanableThreadLocal#initialValue()} because the notifier's thread local
67 * variable will be overwritten and the listeners for the thread will be lost.
68 */
69 private Map getThreadLocalVariable()
70 {
71 Map map = (Map) local.get();
72 return map;
73 }
74
75 public Object get(String key)
76 {
77 Map map = getThreadLocalVariable();
78
79 return map.get(key);
80 }
81
82 public void put(String key, Object value)
83 {
84 Map map = getThreadLocalVariable();
85
86 map.put(key, value);
87 }
88
89 public boolean containsKey(String key)
90 {
91 Map map = getThreadLocalVariable();
92
93 return map.containsKey(key);
94 }
95
96 public void clear()
97 {
98 Map map = (Map) local.get();
99
100 if (map != null)
101 {
102 map.clear();
103 }
104 }
105 }