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.ReentrantLock;
23
24 import org.apache.ibatis.cache.Cache;
25
26
27
28
29
30
31
32
33 public class WeakCache implements Cache {
34 private final Deque<Object> hardLinksToAvoidGarbageCollection;
35 private final ReferenceQueue<Object> queueOfGarbageCollectedEntries;
36 private final Cache delegate;
37 private int numberOfHardLinks;
38 private final ReentrantLock lock = new ReentrantLock();
39
40 public WeakCache(Cache delegate) {
41 this.delegate = delegate;
42 this.numberOfHardLinks = 256;
43 this.hardLinksToAvoidGarbageCollection = new LinkedList<>();
44 this.queueOfGarbageCollectedEntries = new ReferenceQueue<>();
45 }
46
47 @Override
48 public String getId() {
49 return delegate.getId();
50 }
51
52 @Override
53 public int getSize() {
54 removeGarbageCollectedItems();
55 return delegate.getSize();
56 }
57
58 public void setSize(int size) {
59 this.numberOfHardLinks = size;
60 }
61
62 @Override
63 public void putObject(Object key, Object value) {
64 removeGarbageCollectedItems();
65 delegate.putObject(key, new WeakEntry(key, value, queueOfGarbageCollectedEntries));
66 }
67
68 @Override
69 public Object getObject(Object key) {
70 Object result = null;
71 @SuppressWarnings("unchecked")
72 WeakReference<Object> weakReference = (WeakReference<Object>) delegate.getObject(key);
73 if (weakReference != null) {
74 result = weakReference.get();
75 if (result == null) {
76 delegate.removeObject(key);
77 } else {
78 lock.lock();
79 try {
80 hardLinksToAvoidGarbageCollection.addFirst(result);
81 if (hardLinksToAvoidGarbageCollection.size() > numberOfHardLinks) {
82 hardLinksToAvoidGarbageCollection.removeLast();
83 }
84 } finally {
85 lock.unlock();
86 }
87 }
88 }
89 return result;
90 }
91
92 @Override
93 public Object removeObject(Object key) {
94 removeGarbageCollectedItems();
95 @SuppressWarnings("unchecked")
96 WeakReference<Object> weakReference = (WeakReference<Object>) delegate.removeObject(key);
97 return weakReference == null ? null : weakReference.get();
98 }
99
100 @Override
101 public void clear() {
102 lock.lock();
103 try {
104 hardLinksToAvoidGarbageCollection.clear();
105 } finally {
106 lock.unlock();
107 }
108 removeGarbageCollectedItems();
109 delegate.clear();
110 }
111
112 private void removeGarbageCollectedItems() {
113 WeakEntry sv;
114 while ((sv = (WeakEntry) queueOfGarbageCollectedEntries.poll()) != null) {
115 delegate.removeObject(sv.key);
116 }
117 }
118
119 private static class WeakEntry extends WeakReference<Object> {
120 private final Object key;
121
122 private WeakEntry(Object key, Object value, ReferenceQueue<Object> garbageCollectionQueue) {
123 super(value, garbageCollectionQueue);
124 this.key = key;
125 }
126 }
127
128 }