1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.cache.decorators;
17
18 import java.lang.ref.ReferenceQueue;
19 import java.lang.ref.WeakReference;
20 import java.util.Deque;
21 import java.util.LinkedList;
22 import java.util.concurrent.locks.ReadWriteLock;
23
24 import org.apache.ibatis.cache.Cache;
25
26
27
28
29
30
31
32 public class WeakCache implements Cache {
33 private final Deque<Object> hardLinksToAvoidGarbageCollection;
34 private final ReferenceQueue<Object> queueOfGarbageCollectedEntries;
35 private final Cache delegate;
36 private int numberOfHardLinks;
37
38 public WeakCache(Cache delegate) {
39 this.delegate = delegate;
40 this.numberOfHardLinks = 256;
41 this.hardLinksToAvoidGarbageCollection = new LinkedList<Object>();
42 this.queueOfGarbageCollectedEntries = new ReferenceQueue<Object>();
43 }
44
45 @Override
46 public String getId() {
47 return delegate.getId();
48 }
49
50 @Override
51 public int getSize() {
52 removeGarbageCollectedItems();
53 return delegate.getSize();
54 }
55
56 public void setSize(int size) {
57 this.numberOfHardLinks = size;
58 }
59
60 @Override
61 public void putObject(Object key, Object value) {
62 removeGarbageCollectedItems();
63 delegate.putObject(key, new WeakEntry(key, value, queueOfGarbageCollectedEntries));
64 }
65
66 @Override
67 public Object getObject(Object key) {
68 Object result = null;
69 @SuppressWarnings("unchecked")
70 WeakReference<Object> weakReference = (WeakReference<Object>) delegate.getObject(key);
71 if (weakReference != null) {
72 result = weakReference.get();
73 if (result == null) {
74 delegate.removeObject(key);
75 } else {
76 hardLinksToAvoidGarbageCollection.addFirst(result);
77 if (hardLinksToAvoidGarbageCollection.size() > numberOfHardLinks) {
78 hardLinksToAvoidGarbageCollection.removeLast();
79 }
80 }
81 }
82 return result;
83 }
84
85 @Override
86 public Object removeObject(Object key) {
87 removeGarbageCollectedItems();
88 return delegate.removeObject(key);
89 }
90
91 @Override
92 public void clear() {
93 hardLinksToAvoidGarbageCollection.clear();
94 removeGarbageCollectedItems();
95 delegate.clear();
96 }
97
98 @Override
99 public ReadWriteLock getReadWriteLock() {
100 return null;
101 }
102
103 private void removeGarbageCollectedItems() {
104 WeakEntry sv;
105 while ((sv = (WeakEntry) queueOfGarbageCollectedEntries.poll()) != null) {
106 delegate.removeObject(sv.key);
107 }
108 }
109
110 private static class WeakEntry extends WeakReference<Object> {
111 private final Object key;
112
113 private WeakEntry(Object key, Object value, ReferenceQueue<Object> garbageCollectionQueue) {
114 super(value, garbageCollectionQueue);
115 this.key = key;
116 }
117 }
118
119 }