FifoCache.java

  1. /*
  2.  *    Copyright 2009-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.apache.ibatis.cache.decorators;

  17. import java.util.Deque;
  18. import java.util.LinkedList;

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

  20. /**
  21.  * FIFO (first in, first out) cache decorator.
  22.  *
  23.  * @author Clinton Begin
  24.  */
  25. public class FifoCache implements Cache {

  26.   private final Cache delegate;
  27.   private final Deque<Object> keyList;
  28.   private int size;

  29.   public FifoCache(Cache delegate) {
  30.     this.delegate = delegate;
  31.     this.keyList = new LinkedList<>();
  32.     this.size = 1024;
  33.   }

  34.   @Override
  35.   public String getId() {
  36.     return delegate.getId();
  37.   }

  38.   @Override
  39.   public int getSize() {
  40.     return delegate.getSize();
  41.   }

  42.   public void setSize(int size) {
  43.     this.size = size;
  44.   }

  45.   @Override
  46.   public void putObject(Object key, Object value) {
  47.     cycleKeyList(key);
  48.     delegate.putObject(key, value);
  49.   }

  50.   @Override
  51.   public Object getObject(Object key) {
  52.     return delegate.getObject(key);
  53.   }

  54.   @Override
  55.   public Object removeObject(Object key) {
  56.     keyList.remove(key);
  57.     return delegate.removeObject(key);
  58.   }

  59.   @Override
  60.   public void clear() {
  61.     delegate.clear();
  62.     keyList.clear();
  63.   }

  64.   private void cycleKeyList(Object key) {
  65.     keyList.addLast(key);
  66.     if (keyList.size() > size) {
  67.       Object oldestKey = keyList.removeFirst();
  68.       delegate.removeObject(oldestKey);
  69.     }
  70.   }

  71. }