View Javadoc
1   /*
2    *    Copyright 2016-2023 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.mybatis.caches.caffeine;
17  
18  import com.github.benmanes.caffeine.cache.Caffeine;
19  
20  import java.util.concurrent.locks.ReadWriteLock;
21  
22  import org.apache.ibatis.cache.Cache;
23  
24  /**
25   * Cache adapter for Caffeine.
26   *
27   * @author EddĂș MelĂ©ndez
28   */
29  public final class CaffeineCache implements Cache {
30  
31    private com.github.benmanes.caffeine.cache.Cache<Object, Object> cache;
32  
33    private String id;
34  
35    /**
36     * Instantiates a new caffeine cache.
37     *
38     * @param id
39     *          the id
40     */
41    public CaffeineCache(String id) {
42      if (id == null) {
43        throw new IllegalArgumentException("Cache instances require an ID");
44      }
45  
46      this.cache = Caffeine.newBuilder().build();
47      this.id = id;
48    }
49  
50    @Override
51    public String getId() {
52      return this.id;
53    }
54  
55    @Override
56    public void putObject(Object key, Object value) {
57      // Do not allow null values to be cached as not allowed in caffeine cache
58      if (key != null && value != null) {
59        this.cache.put(key, value);
60      }
61    }
62  
63    @Override
64    public Object getObject(Object key) {
65      return this.cache.getIfPresent(key);
66    }
67  
68    @Override
69    public Object removeObject(Object key) {
70      return this.cache.asMap().remove(key);
71    }
72  
73    @Override
74    public void clear() {
75      this.cache.invalidateAll();
76    }
77  
78    @Override
79    public int getSize() {
80      return (int) this.cache.estimatedSize();
81    }
82  
83    @Override
84    public ReadWriteLock getReadWriteLock() {
85      return null;
86    }
87  
88  }