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.util.concurrent.TimeUnit;
19
20 import org.apache.ibatis.cache.Cache;
21
22
23
24
25 public class ScheduledCache implements Cache {
26
27 private final Cache delegate;
28 protected long clearInterval;
29 protected long lastClear;
30
31 public ScheduledCache(Cache delegate) {
32 this.delegate = delegate;
33 this.clearInterval = TimeUnit.HOURS.toMillis(1);
34 this.lastClear = System.currentTimeMillis();
35 }
36
37 public void setClearInterval(long clearInterval) {
38 this.clearInterval = clearInterval;
39 }
40
41 @Override
42 public String getId() {
43 return delegate.getId();
44 }
45
46 @Override
47 public int getSize() {
48 clearWhenStale();
49 return delegate.getSize();
50 }
51
52 @Override
53 public void putObject(Object key, Object object) {
54 clearWhenStale();
55 delegate.putObject(key, object);
56 }
57
58 @Override
59 public Object getObject(Object key) {
60 return clearWhenStale() ? null : delegate.getObject(key);
61 }
62
63 @Override
64 public Object removeObject(Object key) {
65 clearWhenStale();
66 return delegate.removeObject(key);
67 }
68
69 @Override
70 public void clear() {
71 lastClear = System.currentTimeMillis();
72 delegate.clear();
73 }
74
75 @Override
76 public int hashCode() {
77 return delegate.hashCode();
78 }
79
80 @Override
81 public boolean equals(Object obj) {
82 return delegate.equals(obj);
83 }
84
85 private boolean clearWhenStale() {
86 if (System.currentTimeMillis() - lastClear > clearInterval) {
87 clear();
88 return true;
89 }
90 return false;
91 }
92
93 }