Class SimpleCache<K,V>

java.lang.Object
org.aoju.bus.core.lang.SimpleCache<K,V>
Type Parameters:
K - 键类型
V - 值类型
All Implemented Interfaces:
Serializable, Iterable<Map.Entry<K,V>>

public class SimpleCache<K,V> extends Object implements Iterable<Map.Entry<K,V>>, Serializable
简单缓存,无超时实现,使用WeakMap实现缓存自动清理
Since:
Java 17+
Author:
Kimi Liu
See Also:
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    protected final Map<K,Lock>
    写的时候每个key一把锁,降低锁的粒度
  • Constructor Summary

    Constructors
    Constructor
    Description
    构造,默认使用WeakHashMap实现缓存自动清理
    SimpleCache(Map<K,V> initMap)
    通过自定义Map初始化,可以自定义缓存实现 比如使用WeakHashMap则会自动清理key,使用HashMap则不会清理 同时,传入的Map对象也可以自带初始化的键值对,防止在get时创建
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    清空缓存池
    get(K key)
    从缓存池中查找值
    get(K key, Predicate<V> validPredicate, Func0<V> supplier)
    从缓存中获得对象,当对象不在缓存中或已经过期返回Func0回调产生的对象
    get(K key, Func0<V> supplier)
    从缓存中获得对象,当对象不在缓存中或已经过期返回Func0回调产生的对象
     
    put(K key, V value)
    放入缓存
    remove(K key)
    移除缓存

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

    Methods inherited from interface java.lang.Iterable

    forEach, spliterator
  • Field Details

    • keyLockMap

      protected final Map<K,Lock> keyLockMap
      写的时候每个key一把锁,降低锁的粒度
  • Constructor Details

    • SimpleCache

      public SimpleCache()
      构造,默认使用WeakHashMap实现缓存自动清理
    • SimpleCache

      public SimpleCache(Map<K,V> initMap)
      通过自定义Map初始化,可以自定义缓存实现 比如使用WeakHashMap则会自动清理key,使用HashMap则不会清理 同时,传入的Map对象也可以自带初始化的键值对,防止在get时创建
      Parameters:
      initMap - 初始Map,用于定义Map类型
  • Method Details

    • get

      public V get(K key)
      从缓存池中查找值
      Parameters:
      key - 键
      Returns:
    • get

      public V get(K key, Func0<V> supplier)
      从缓存中获得对象,当对象不在缓存中或已经过期返回Func0回调产生的对象
      Parameters:
      key - 键
      supplier - 如果不存在回调方法,用于生产值对象
      Returns:
      值对象
    • get

      public V get(K key, Predicate<V> validPredicate, Func0<V> supplier)
      从缓存中获得对象,当对象不在缓存中或已经过期返回Func0回调产生的对象
      Parameters:
      key - 键
      validPredicate - 检查结果对象是否可用,如是否断开连接等
      supplier - 如果不存在回调方法或结果不可用,用于生产值对象
      Returns:
      值对象
    • put

      public V put(K key, V value)
      放入缓存
      Parameters:
      key - 键
      value - 值
      Returns:
    • remove

      public V remove(K key)
      移除缓存
      Parameters:
      key - 键
      Returns:
      移除的值
    • clear

      public void clear()
      清空缓存池
    • iterator

      public Iterator<Map.Entry<K,V>> iterator()
      Specified by:
      iterator in interface Iterable<K>