Class ReentrantCache<K,V>

java.lang.Object
org.miaixz.bus.core.cache.provider.AbstractCache<K,V>
org.miaixz.bus.core.cache.provider.ReentrantCache<K,V>
Type Parameters:
K - 键类型
V - 值类型
All Implemented Interfaces:
Serializable, Iterable<V>, Cache<K,V>
Direct Known Subclasses:
LRUCache

public abstract class ReentrantCache<K,V> extends AbstractCache<K,V>
使用ReentrantLock保护的缓存,读写都使用悲观锁完成,主要避免某些Map无法使用读写锁的问题 例如使用了LinkedHashMap的缓存,由于get方法也会改变Map的结构,因此读写必须加互斥锁
Since:
Java 17+
Author:
Kimi Liu
See Also:
  • Field Details

    • lock

      protected final ReentrantLock lock
      特殊缓存,例如使用了LinkedHashMap的缓存,由于get方法也会改变Map的结构,导致无法使用读写锁
  • Constructor Details

    • ReentrantCache

      public ReentrantCache()
  • Method Details

    • put

      public void put(K key, V object, long timeout)
      Description copied from interface: Cache
      将对象加入到缓存,使用指定失效时长 如果缓存空间满了,Cache.prune() 将被调用以获得空间来存放新对象
      Parameters:
      key - 键
      object - 缓存的对象
      timeout - 失效时长,单位毫秒
    • containsKey

      public boolean containsKey(K key)
      Description copied from interface: Cache
      是否包含key
      Parameters:
      key - KEY
      Returns:
      是否包含key
    • get

      public V get(K key, boolean isUpdateLastAccess)
      Description copied from interface: Cache
      从缓存中获得对象,当对象不在缓存中或已经过期返回null

      调用此方法时,会检查上次调用时间,如果与当前时间差值大于超时时间返回null,否则返回值。

      每次调用此方法会可选是否刷新最后访问时间,true表示会重新计算超时时间。

      Parameters:
      key - 键
      isUpdateLastAccess - 是否更新最后访问时间,即重新计算超时时间。
      Returns:
      键对应的对象
    • cacheObjIterator

      public Iterator<CacheObject<K,V>> cacheObjIterator()
      Description copied from interface: Cache
      返回包含键和值得迭代器
      Returns:
      缓存对象迭代器
    • prune

      public final int prune()
      Description copied from interface: Cache
      从缓存中清理过期对象,清理策略取决于具体实现
      Returns:
      清理的缓存对象个数
    • remove

      public void remove(K key)
      Description copied from interface: Cache
      从缓存中移除对象
      Parameters:
      key - 键
    • clear

      public void clear()
      Description copied from interface: Cache
      清空缓存
    • toString

      public String toString()
      Overrides:
      toString in class AbstractCache<K,V>