View Javadoc
1   /*
2    *    Copyright 2009-2021 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    *       http://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.Deque;
19  import java.util.LinkedList;
20  
21  import org.apache.ibatis.cache.Cache;
22  
23  /**
24   * FIFO (first in, first out) cache decorator.
25   *
26   * @author Clinton Begin
27   */
28  public class FifoCache implements Cache {
29  
30    private final Cache delegate;
31    private final Deque<Object> keyList;
32    private int size;
33  
34    public FifoCache(Cache delegate) {
35      this.delegate = delegate;
36      this.keyList = new LinkedList<>();
37      this.size = 1024;
38    }
39  
40    @Override
41    public String getId() {
42      return delegate.getId();
43    }
44  
45    @Override
46    public int getSize() {
47      return delegate.getSize();
48    }
49  
50    public void setSize(int size) {
51      this.size = size;
52    }
53  
54    @Override
55    public void putObject(Object key, Object value) {
56      cycleKeyList(key);
57      delegate.putObject(key, value);
58    }
59  
60    @Override
61    public Object getObject(Object key) {
62      return delegate.getObject(key);
63    }
64  
65    @Override
66    public Object removeObject(Object key) {
67      return delegate.removeObject(key);
68    }
69  
70    @Override
71    public void clear() {
72      delegate.clear();
73      keyList.clear();
74    }
75  
76    private void cycleKeyList(Object key) {
77      keyList.addLast(key);
78      if (keyList.size() > size) {
79        Object oldestKey = keyList.removeFirst();
80        delegate.removeObject(oldestKey);
81      }
82    }
83  
84  }