CaffeineCache.java

  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. import com.github.benmanes.caffeine.cache.Caffeine;

  18. import java.util.concurrent.locks.ReadWriteLock;

  19. import org.apache.ibatis.cache.Cache;

  20. /**
  21.  * Cache adapter for Caffeine.
  22.  *
  23.  * @author EddĂș MelĂ©ndez
  24.  */
  25. public final class CaffeineCache implements Cache {

  26.   private com.github.benmanes.caffeine.cache.Cache<Object, Object> cache;

  27.   private String id;

  28.   /**
  29.    * Instantiates a new caffeine cache.
  30.    *
  31.    * @param id
  32.    *          the id
  33.    */
  34.   public CaffeineCache(String id) {
  35.     if (id == null) {
  36.       throw new IllegalArgumentException("Cache instances require an ID");
  37.     }

  38.     this.cache = Caffeine.newBuilder().build();
  39.     this.id = id;
  40.   }

  41.   @Override
  42.   public String getId() {
  43.     return this.id;
  44.   }

  45.   @Override
  46.   public void putObject(Object key, Object value) {
  47.     // Do not allow null values to be cached as not allowed in caffeine cache
  48.     if (key != null && value != null) {
  49.       this.cache.put(key, value);
  50.     }
  51.   }

  52.   @Override
  53.   public Object getObject(Object key) {
  54.     return this.cache.getIfPresent(key);
  55.   }

  56.   @Override
  57.   public Object removeObject(Object key) {
  58.     return this.cache.asMap().remove(key);
  59.   }

  60.   @Override
  61.   public void clear() {
  62.     this.cache.invalidateAll();
  63.   }

  64.   @Override
  65.   public int getSize() {
  66.     return (int) this.cache.estimatedSize();
  67.   }

  68.   @Override
  69.   public ReadWriteLock getReadWriteLock() {
  70.     return null;
  71.   }

  72. }