View Javadoc
1   /*
2    *    Copyright 2009-2022 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
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   * @author Clinton Begin
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  }