ScheduledCache.java

  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.decorators;

  17. import java.util.concurrent.TimeUnit;

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

  19. /**
  20.  * @author Clinton Begin
  21.  */
  22. public class ScheduledCache implements Cache {

  23.   private final Cache delegate;
  24.   protected long clearInterval;
  25.   protected long lastClear;

  26.   public ScheduledCache(Cache delegate) {
  27.     this.delegate = delegate;
  28.     this.clearInterval = TimeUnit.HOURS.toMillis(1);
  29.     this.lastClear = System.currentTimeMillis();
  30.   }

  31.   public void setClearInterval(long clearInterval) {
  32.     this.clearInterval = clearInterval;
  33.   }

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

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

  43.   @Override
  44.   public void putObject(Object key, Object object) {
  45.     clearWhenStale();
  46.     delegate.putObject(key, object);
  47.   }

  48.   @Override
  49.   public Object getObject(Object key) {
  50.     return clearWhenStale() ? null : delegate.getObject(key);
  51.   }

  52.   @Override
  53.   public Object removeObject(Object key) {
  54.     clearWhenStale();
  55.     return delegate.removeObject(key);
  56.   }

  57.   @Override
  58.   public void clear() {
  59.     lastClear = System.currentTimeMillis();
  60.     delegate.clear();
  61.   }

  62.   @Override
  63.   public int hashCode() {
  64.     return delegate.hashCode();
  65.   }

  66.   @Override
  67.   public boolean equals(Object obj) {
  68.     return delegate.equals(obj);
  69.   }

  70.   private boolean clearWhenStale() {
  71.     if (System.currentTimeMillis() - lastClear > clearInterval) {
  72.       clear();
  73.       return true;
  74.     }
  75.     return false;
  76.   }

  77. }