PerpetualCache.java

  1. /*
  2.  *    Copyright 2009-2024 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. import java.util.HashMap;
  18. import java.util.Map;

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

  21. /**
  22.  * @author Clinton Begin
  23.  */
  24. public class PerpetualCache implements Cache {

  25.   private final String id;

  26.   private final Map<Object, Object> cache = new HashMap<>();

  27.   public PerpetualCache(String id) {
  28.     this.id = id;
  29.   }

  30.   @Override
  31.   public String getId() {
  32.     return id;
  33.   }

  34.   @Override
  35.   public int getSize() {
  36.     return cache.size();
  37.   }

  38.   @Override
  39.   public void putObject(Object key, Object value) {
  40.     cache.put(key, value);
  41.   }

  42.   @Override
  43.   public Object getObject(Object key) {
  44.     return cache.get(key);
  45.   }

  46.   @Override
  47.   public Object removeObject(Object key) {
  48.     return cache.remove(key);
  49.   }

  50.   @Override
  51.   public void clear() {
  52.     cache.clear();
  53.   }

  54.   @Override
  55.   public boolean equals(Object o) {
  56.     if (getId() == null) {
  57.       throw new CacheException("Cache instances require an ID.");
  58.     }
  59.     if (this == o) {
  60.       return true;
  61.     }
  62.     if (!(o instanceof Cache)) {
  63.       return false;
  64.     }

  65.     Cache otherCache = (Cache) o;
  66.     return getId().equals(otherCache.getId());
  67.   }

  68.   @Override
  69.   public int hashCode() {
  70.     if (getId() == null) {
  71.       throw new CacheException("Cache instances require an ID.");
  72.     }
  73.     return getId().hashCode();
  74.   }

  75. }