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