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.SoftReference;
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
32 public class SoftCache 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 SoftCache(Cache delegate) {
39 this.delegate = delegate;
40 this.numberOfHardLinks = 256;
41 this.hardLinksToAvoidGarbageCollection = new LinkedList<>();
42 this.queueOfGarbageCollectedEntries = new ReferenceQueue<>();
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 SoftEntry(key, value, queueOfGarbageCollectedEntries));
64 }
65
66 @Override
67 public Object getObject(Object key) {
68 Object result = null;
69 @SuppressWarnings("unchecked")
70 SoftReference<Object> softReference = (SoftReference<Object>) delegate.getObject(key);
71 if (softReference != null) {
72 result = softReference.get();
73 if (result == null) {
74 delegate.removeObject(key);
75 } else {
76
77 synchronized (hardLinksToAvoidGarbageCollection) {
78 hardLinksToAvoidGarbageCollection.addFirst(result);
79 if (hardLinksToAvoidGarbageCollection.size() > numberOfHardLinks) {
80 hardLinksToAvoidGarbageCollection.removeLast();
81 }
82 }
83 }
84 }
85 return result;
86 }
87
88 @Override
89 public Object removeObject(Object key) {
90 removeGarbageCollectedItems();
91 @SuppressWarnings("unchecked")
92 SoftReference<Object> softReference = (SoftReference<Object>) delegate.removeObject(key);
93 return softReference == null ? null : softReference.get();
94 }
95
96 @Override
97 public void clear() {
98 synchronized (hardLinksToAvoidGarbageCollection) {
99 hardLinksToAvoidGarbageCollection.clear();
100 }
101 removeGarbageCollectedItems();
102 delegate.clear();
103 }
104
105 private void removeGarbageCollectedItems() {
106 SoftEntry sv;
107 while ((sv = (SoftEntry) queueOfGarbageCollectedEntries.poll()) != null) {
108 delegate.removeObject(sv.key);
109 }
110 }
111
112 private static class SoftEntry extends SoftReference<Object> {
113 private final Object key;
114
115 SoftEntry(Object key, Object value, ReferenceQueue<Object> garbageCollectionQueue) {
116 super(value, garbageCollectionQueue);
117 this.key = key;
118 }
119 }
120
121 }