1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package de.bea.domingo.cache;
24
25 import java.io.Serializable;
26 import java.lang.ref.WeakReference;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.WeakHashMap;
32
33 /***
34 * Weak Cache.
35 *
36 * <p>This implementation of the <code>Cache</code> interface uses
37 * a <code>WeakHashMap</code> to store the keys. The values are stored
38 * as <code>WeakReference</code>s.</p>
39 *
40 * <p><b>Note that this implementation is synchronized.</b> Multiple
41 * threads can access this map concurrently.</p>
42 *
43 * @see java.util.WeakHashMap
44 * @see java.lang.ref.WeakReference
45 *
46 * @author <a href=mailto:kriede@users.sourceforge.net>Kurt Riede</a>
47 */
48 public final class WeakCache extends AbstractBaseCache implements Serializable {
49
50 /*** serial version ID for serialization. */
51 private static final long serialVersionUID = -4673439673337362588L;
52
53 /***
54 * Creates a new WeakCache object.
55 */
56 public WeakCache() {
57 super();
58 }
59
60 /***
61 * {@inheritDoc}
62 * @see de.bea.domingo.cache.AbstractBaseCache#createMap()
63 */
64 protected Map createMap() {
65 return new WeakHashMap();
66 }
67
68 /***
69 * {@inheritDoc}
70 * @see de.bea.domingo.cache.Cache#put(java.lang.Object, java.lang.Object)
71 * @see java.lang.ref.WeakReference
72 * @see de.bea.domingo.cache.Cache#put(java.lang.Object, java.lang.Object)
73 */
74 public synchronized void put(final Object key, final Object value) {
75 getMap().put(key, new WeakReference(value));
76 }
77
78 /***
79 * {@inheritDoc}
80 * @see de.bea.domingo.cache.Cache#get(java.lang.Object)
81 */
82 public synchronized Object get(final Object key) {
83 final WeakReference reference = (WeakReference) getMap().get(key);
84 if (reference != null) {
85 return reference.get();
86 }
87 return null;
88 }
89
90 /***
91 * {@inheritDoc}
92 * @see de.bea.domingo.cache.Cache#containsKey(java.lang.Object)
93 */
94 public synchronized boolean containsKey(final Object key) {
95 return getMap().containsKey(key);
96 }
97
98 /***
99 * {@inheritDoc}
100 * @see de.bea.domingo.cache.Cache#remove(java.lang.Object)
101 */
102 public synchronized Object remove(final Object key) {
103 return getMap().remove(key);
104 }
105
106 /***
107 * {@inheritDoc}
108 * @see de.bea.domingo.cache.Cache#clear()
109 */
110 public void clear() {
111 getMap().clear();
112 }
113
114 /***
115 * {@inheritDoc}
116 * @see de.bea.domingo.cache.AbstractBaseCache#keySet()
117 */
118 public Set keySet() {
119 return Collections.synchronizedSet(getMap().keySet());
120 }
121
122 /***
123 * {@inheritDoc}
124 * @see de.bea.domingo.cache.AbstractBaseCache#values()
125 */
126 public Collection values() {
127 return Collections.synchronizedCollection(getMap().values());
128 }
129 }