1
2 package net.sf.voruta;
3
4 import java.util.*;
5 import java.lang.ref.*;
6 /***
7 *@author Juozas Baliuka <a href="mailto:baliuka@mwm.lt">
8 * baliuka@mwm.lt</a>
9 *@author Gerhard Froehlich <a href="mailto:g-froehlich@gmx.de">
10 * g-froehlich@gmx.de</a>
11 *@version $Id: SoftRefMemoryCache.java,v 1.7 2003/07/29 09:26:04 baliuka Exp $
12 */
13 final class SoftRefMemoryCache {
14
15 private static int current = 0;
16 private static final int MAX_STRONG_REF = 255;
17 private Map m_map = new Hashtable();
18 private static Object[] strongRefs = new Object[MAX_STRONG_REF];
19 private static ReferenceQueue queue = new ReferenceQueue();
20
21
22 /***
23 * Get the object associated to the given unique key.
24 *
25 *@param key the Key Object
26 *@return requested object or null
27 */
28 Object get(Object key) {
29
30 removeSoftRef();
31 Object object = null;
32 SoftRef ref = (SoftRef) m_map.get(key);
33
34 if (ref != null) {
35 object = ref.get();
36 }
37
38 addStrongRef(object);
39
40
41 return object;
42 }
43
44 /***
45 * Cache the object associated to the given unique key.
46 *
47 *@param key the key object
48 *@param object
49 */
50 void put(Object key, Object object) {
51 removeSoftRef();
52 internalStoreObject(key, object);
53 }
54
55 void putAll(SoftRefMemoryCache cache){
56 removeSoftRef();
57 m_map.putAll(cache.m_map);
58 }
59
60 void clear(){
61 DbUtils.getLog().debug("SoftRefMemoryCache.clear()");
62 removeSoftRef();
63 m_map.clear();
64
65 }
66
67 private SoftRef makeValue(Object key, Object value, ReferenceQueue queue) {
68 return new SoftRef(key, value, queue);
69 }
70
71 // remove unused keys
72 private void removeSoftRef() {
73 SoftRef ref = (SoftRef) queue.poll();
74
75 while (ref != null) {
76 m_map.remove(ref.key);
77 ref = (SoftRef) queue.poll();
78 }
79 }
80
81 private void addStrongRef(Object object) {
82 if (strongRefs != null) {
83 synchronized(strongRefs){
84 strongRefs[(current++) % MAX_STRONG_REF] = object;
85 }
86 }
87 }
88
89 private void internalStoreObject(Object key, Object object) {
90 SoftRef ref = makeValue(key, object, queue);
91 addStrongRef(ref.get());
92 m_map.put(key, ref);
93 }
94
95 final static class SoftRef extends SoftReference {
96 private Object key;
97
98 private SoftRef(Object key, Object object, ReferenceQueue queue) {
99 super(object, queue);
100 this.key = key;
101 }
102 }
103 }
This page was automatically generated by Maven