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
23 import org.apache.ibatis.cache.Cache;
24
25
26
27
28
29
30
31 public class WeakCache implements Cache {
32 private final Deque<Object> hardLinksToAvoidGarbageCollection;
33 private final ReferenceQueue<Object> queueOfGarbageCollectedEntries;
34 private final Cache delegate;
35 private int numberOfHardLinks;
36
37 public WeakCache(Cache delegate) {
38 this.delegate = delegate;
39 this.numberOfHardLinks = 256;
40 this.hardLinksToAvoidGarbageCollection = new LinkedList<>();
41 this.queueOfGarbageCollectedEntries = new ReferenceQueue<>();
42 }
43
44 @Override
45 public String getId() {
46 return delegate.getId();
47 }
48
49 @Override
50 public int getSize() {
51 removeGarbageCollectedItems();
52 return delegate.getSize();
53 }
54
55 public void setSize(int size) {
56 this.numberOfHardLinks = size;
57 }
58
59 @Override
60 public void putObject(Object key, Object value) {
61 removeGarbageCollectedItems();
62 delegate.putObject(key, new WeakEntry(key, value, queueOfGarbageCollectedEntries));
63 }
64
65 @Override
66 public Object getObject(Object key) {
67 Object result = null;
68 @SuppressWarnings("unchecked")
69 WeakReference<Object> weakReference = (WeakReference<Object>) delegate.getObject(key);
70 if (weakReference != null) {
71 result = weakReference.get();
72 if (result == null) {
73 delegate.removeObject(key);
74 } else {
75 synchronized (hardLinksToAvoidGarbageCollection) {
76 hardLinksToAvoidGarbageCollection.addFirst(result);
77 if (hardLinksToAvoidGarbageCollection.size() > numberOfHardLinks) {
78 hardLinksToAvoidGarbageCollection.removeLast();
79 }
80 }
81 }
82 }
83 return result;
84 }
85
86 @Override
87 public Object removeObject(Object key) {
88 removeGarbageCollectedItems();
89 @SuppressWarnings("unchecked")
90 WeakReference<Object> weakReference = (WeakReference<Object>) delegate.removeObject(key);
91 return weakReference == null ? null : weakReference.get();
92 }
93
94 @Override
95 public void clear() {
96 synchronized (hardLinksToAvoidGarbageCollection) {
97 hardLinksToAvoidGarbageCollection.clear();
98 }
99 removeGarbageCollectedItems();
100 delegate.clear();
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 }