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.impl;
17  
18  import java.util.HashMap;
19  import java.util.Map;
20  
21  import org.apache.ibatis.cache.Cache;
22  import org.apache.ibatis.cache.CacheException;
23  
24  /**
25   * @author Clinton Begin
26   */
27  public class PerpetualCache implements Cache {
28  
29    private final String id;
30  
31    private final Map<Object, Object> cache = new HashMap<>();
32  
33    public PerpetualCache(String id) {
34      this.id = id;
35    }
36  
37    @Override
38    public String getId() {
39      return id;
40    }
41  
42    @Override
43    public int getSize() {
44      return cache.size();
45    }
46  
47    @Override
48    public void putObject(Object key, Object value) {
49      cache.put(key, value);
50    }
51  
52    @Override
53    public Object getObject(Object key) {
54      return cache.get(key);
55    }
56  
57    @Override
58    public Object removeObject(Object key) {
59      return cache.remove(key);
60    }
61  
62    @Override
63    public void clear() {
64      cache.clear();
65    }
66  
67    @Override
68    public boolean equals(Object o) {
69      if (getId() == null) {
70        throw new CacheException("Cache instances require an ID.");
71      }
72      if (this == o) {
73        return true;
74      }
75      if (!(o instanceof Cache)) {
76        return false;
77      }
78  
79      Cache otherCache = (Cache) o;
80      return getId().equals(otherCache.getId());
81    }
82  
83    @Override
84    public int hashCode() {
85      if (getId() == null) {
86        throw new CacheException("Cache instances require an ID.");
87      }
88      return getId().hashCode();
89    }
90  
91  }