Debian Codegraph @

jdbm1/src/main/java/jdbm/helper/SoftCache.java

raw
1 /**
2 * JDBM LICENSE v1.00
3 *
4 * Redistribution and use of this software and associated documentation
5 * ("Software"), with or without modification, are permitted provided
6 * that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain copyright
9 * statements and notices. Redistributions must also contain a
10 * copy of this document.
11 *
12 * 2. Redistributions in binary form must reproduce the
13 * above copyright notice, this list of conditions and the
14 * following disclaimer in the documentation and/or other
15 * materials provided with the distribution.
16 *
17 * 3. The name "JDBM" must not be used to endorse or promote
18 * products derived from this Software without prior written
19 * permission of Cees de Groot. For written permission,
20 * please contact [email protected].
21 *
22 * 4. Products derived from this Software may not be called "JDBM"
23 * nor may "JDBM" appear in their names without prior written
24 * permission of Cees de Groot.
25 *
26 * 5. Due credit should be given to the JDBM Project
27 * (http://jdbm.sourceforge.net/).
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE JDBM PROJECT AND CONTRIBUTORS
30 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
31 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
32 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
33 * CEES DE GROOT OR ANY CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
34 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
35 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
36 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
38 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
40 * OF THE POSSIBILITY OF SUCH DAMAGE.
41 *
42 * Copyright 2000 (C) Cees de Groot. All Rights Reserved.
43 * Contributions are Copyright (C) 2000 by their associated contributors.
44 *
45 * $Id
46 */
47 package jdbm.helper;
48
49
50 import java.lang.ref.Reference;
51 import java.lang.ref.ReferenceQueue;
52 import java.lang.ref.SoftReference;
53 import java.util.Enumeration;
54 import java.util.HashMap;
55 import java.util.Map;
56
57 import jdbm.I18n;
58
59
60 /**
61 * Wraps a deterministic cache policy with a <q>Level-2</q> cache based on
62 * J2SE's {@link SoftReference soft references}. Soft references allow
63 * this cache to keep references to objects until the memory they occupy
64 * is required elsewhere.
65 * <p>
66 * Since the {@link CachePolicy} interface requires an event be fired
67 * when an object is evicted, and the event contains the actual object,
68 * this class cannot be a stand-alone implementation of
69 * <code>CachePolicy</code>. This limitation arises because Java References
70 * does not support notification before references are cleared; nor do
71 * they support reaching soft referents. Therefore, this wrapper cache
72 * aggressively notifies evictions: events are fired when the objects are
73 * evicted from the internal cache. Consequently, the soft cache may return
74 * a non-null object when <code>get( )</code> is called, even if that
75 * object was said to have been evicted.
76 * <p>
77 * The current implementation uses a hash structure for its internal key
78 * to value mappings.
79 * <p>
80 * Note: this component's publicly exposed methods are not threadsafe;
81 * potentially concurrent code should synchronize on the cache instance.
82 *
83 * @author <a href="mailto:[email protected]">Dilum Ranatunga</a>
84 */
85 public class SoftCache implements CachePolicy
86 {
87 private static final int INITIAL_CAPACITY = 128;
88 private static final float DEFAULT_LOAD_FACTOR = 1.5f;
89
90 private final ReferenceQueue clearQueue = new ReferenceQueue();
91 private final CachePolicy internal;
92 private final Map map;
93
94
95 /**
96 * Creates a soft-reference based L2 cache with a {@link MRU} cache as
97 * the internal (L1) cache. The soft reference cache uses the
98 * default load capacity of 1.5f, which is intended to sacrifice some
99 * performance for space. This compromise is reasonable, since all
100 * {@link #get(Object) get( )s} first try the L1 cache anyway. The
101 * internal MRU is given a capacity of 128 elements.
102 */
103 public SoftCache()
104 {
105 this( new MRU( INITIAL_CAPACITY ) );
106 }
107
108
109 /**
110 * Creates a soft-reference based L2 cache wrapping the specified
111 * L1 cache.
112 *
113 * @param internal non null internal cache.
114 * @throws NullPointerException if the internal cache is null.
115 */
116 public SoftCache( CachePolicy internal ) throws NullPointerException
117 {
118 this( DEFAULT_LOAD_FACTOR, internal );
119 }
120
121
122 /**
123 * Creates a soft-reference based L2 cache wrapping the specified
124 * L1 cache. This constructor is somewhat implementation-specific,
125 * so users are encouraged to use {@link #SoftCache(CachePolicy)}
126 * instead.
127 *
128 * @param loadFactor load factor that the soft cache's hash structure
129 * should use.
130 * @param internal non null internal cache.
131 * @throws IllegalArgumentException if the load factor is nonpositive.
132 * @throws NullPointerException if the internal cache is null.
133 */
134 public SoftCache( float loadFactor, CachePolicy internal ) throws IllegalArgumentException, NullPointerException
135 {
136 if ( internal == null )
137 {
138 throw new IllegalArgumentException( I18n.err( I18n.ERR_531 ) );
139 }
140
141 this.internal = internal;
142 map = new HashMap( INITIAL_CAPACITY, loadFactor );
143 }
144
145
146 /**
147 * Adds the specified value to the cache under the specified key. Note
148 * that the object is added to both this and the internal cache.
149 * @param key the (non-null) key to store the object under
150 * @param value the (non-null) object to place in the cache
151 * @throws CacheEvictionException exception that the internal cache
152 * would have experienced while evicting an object it currently
153 * cached.
154 */
155 public void put( Object key, Object value ) throws CacheEvictionException
156 {
157 if ( key == null )
158 {
159 throw new IllegalArgumentException( I18n.err( I18n.ERR_532 ) );
160 }
161 else if ( value == null )
162 {
163 throw new IllegalArgumentException( I18n.err( I18n.ERR_533 ) );
164 }
165
166 internal.put( key, value );
167 removeClearedEntries();
168 map.put( key, new Entry( key, value, clearQueue ) );
169 }
170
171
172 /**
173 * Gets the object cached under the specified key.
174 * <p>
175 * The cache is looked up in the following manner:
176 * <ol>
177 * <li>The internal (L1) cache is checked. If the object is found, it is
178 * returned.</li>
179 * <li>This (L2) cache is checked. If the object is not found, then
180 * the caller is informed that the object is inaccessible.</li>
181 * <li>Since the object exists in L2, but not in L1, the object is
182 * readded to L1 using {@link CachePolicy#put(Object, Object)}.</li>
183 * <li>If the readding succeeds, the value is returned to caller.</li>
184 * <li>If a cache eviction exception is encountered instead, we
185 * remove the object from L2 and behave as if the object was
186 * inaccessible.</li>
187 * </ol>
188 * @param key the key that the object was stored under.
189 * @return the object stored under the key specified; null if the
190 * object is not (nolonger) accessible via this cache.
191 */
192 public Object get( Object key )
193 {
194 // first try the internal cache.
195 Object value = internal.get( key );
196
197 if ( value != null )
198 {
199 return value;
200 }
201
202 // poll and remove cleared references.
203 removeClearedEntries();
204 Entry entry = ( Entry ) map.get( key );
205
206 if ( entry == null )
207 { // object is not in cache.
208 return null;
209 }
210
211 value = entry.getValue();
212
213 if ( value == null )
214 { // object was in cache, but it was cleared.
215 return null;
216 }
217
218 // we have the object. so we try to re-insert it into internal cache
219 try
220 {
221 internal.put( key, value );
222 }
223 catch ( CacheEvictionException e )
224 {
225 // if the internal cache causes a fuss, we kick the object out.
226 map.remove( key );
227 return null;
228 }
229
230 return value;
231 }
232
233
234 /**
235 * Removes any object stored under the key specified. Note that the
236 * object is removed from both this (L2) and the internal (L1)
237 * cache.
238 * @param key the key whose object should be removed
239 */
240 public void remove( Object key )
241 {
242 map.remove( key );
243 internal.remove( key );
244 }
245
246
247 /**
248 * Removes all objects in this (L2) and its internal (L1) cache.
249 */
250 public void removeAll()
251 {
252 map.clear();
253 internal.removeAll();
254 }
255
256
257 /**
258 * Gets all the objects stored by the internal (L1) cache.
259 * @return an enumeration of objects in internal cache.
260 */
261 public Enumeration elements()
262 {
263 return internal.elements();
264 }
265
266
267 /**
268 * Adds the specified listener to this cache. Note that the events
269 * fired by this correspond to the <em>internal</em> cache's events.
270 * @param listener the (non-null) listener to add to this policy
271 * @throws IllegalArgumentException if listener is null.
272 */
273 public void addListener( CachePolicyListener listener ) throws IllegalArgumentException
274 {
275 internal.addListener( listener );
276 }
277
278
279 /**
280 * Removes a listener that was added earlier.
281 * @param listener the listener to remove.
282 */
283 public void removeListener( CachePolicyListener listener )
284 {
285 internal.removeListener( listener );
286 }
287
288
289 /**
290 * Cleans the mapping structure of any obsolete entries. This is usually
291 * called before insertions and lookups on the mapping structure. The
292 * runtime of this is usually very small, but it can be as expensive as
293 * n * log(n) if a large number of soft references were recently cleared.
294 */
295 private final void removeClearedEntries()
296 {
297 for ( Reference r = clearQueue.poll(); r != null; r = clearQueue.poll() )
298 {
299 Object key = ( ( Entry ) r ).getKey();
300 map.remove( key );
301 }
302 }
303
304 /**
305 * Value objects we keep in the internal map. This contains the key in
306 * addition to the value, because polling for cleared references
307 * returns these instances, and having access to their corresponding
308 * keys drastically improves the performance of removing the pair
309 * from the map (see {@link SoftCache#removeClearedEntries()}.)
310 */
311 private static class Entry extends SoftReference
312 {
313 private final Object key;
314
315
316 /**
317 * Constructor that uses <code>value</code> as the soft
318 * reference's referent.
319 */
320 public Entry( Object key, Object value, ReferenceQueue queue )
321 {
322 super( value, queue );
323 this.key = key;
324 }
325
326
327 /**
328 * Gets the key
329 * @return the key associated with this value.
330 */
331 final Object getKey()
332 {
333 return key;
334 }
335
336
337 /**
338 * Gets the value
339 * @return the value; null if it is no longer accessible
340 */
341 final Object getValue()
342 {
343 return this.get();
344 }
345 }
346 }