1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.ashkay.strategies;
17
18 import java.lang.ref.Reference;
19 import java.lang.ref.ReferenceQueue;
20 import java.util.IdentityHashMap;
21 import java.util.Map;
22
23 import net.sf.ashkay.CacheEntry;
24 import net.sf.ashkay.CachingStrategy;
25
26
27 /***
28 * A Soft Reference caching strategy uses soft references to store objects in
29 * the cache. Soft references do not prevent the garbage collection of the
30 * objects.
31 *
32 * @author <a href="mailto:bangroot@users.sf.net">Dave Brown</a>
33 */
34
35 public class SoftReferenceCachingStrategy implements CachingStrategy
36 {
37 private Map entryMap = new IdentityHashMap();
38 private ReferenceQueue queue = new ReferenceQueue();
39
40 public CacheEntry prepare(CacheEntry entry)
41 {
42 checkQueue();
43
44 SoftReferenceCacheEntry theEntry = new SoftReferenceCacheEntry(entry, queue);
45 entryMap.put(theEntry.getEntryReference(), theEntry);
46 return theEntry;
47 }
48
49
50 public boolean validate(CacheEntry entry)
51 {
52 checkQueue();
53
54 boolean val = true;
55 if (entry.getEntryObject() == null)
56 {
57 val = false;
58 }
59
60 return val;
61 }
62
63 private void checkQueue()
64 {
65 Reference ref = queue.poll();
66 while (ref != null)
67 {
68 CacheEntry entryToClear = (CacheEntry) entryMap.get(ref);
69 if (entryToClear != null)
70 {
71 entryToClear.getCache().evict(entryToClear.getEntryKey());
72 entryMap.remove(ref);
73 }
74 ref = queue.poll();
75 }
76 }
77 }