zoukankan      html  css  js  c++  java
  • Guava Cache

    Guava Cache 是做什么的?

    内存缓存,类似于 ConcurrentMap,支持自动缓存、缓存回收和缓存移除回调。

    两种加载方式

    使用CacheLoader

    当有默认的加载或计算方式使用该方式。示例如下:

    LoadingCache<Key, Value> cache = CacheBuilder.newBuilder()
        .maximumSize(1000)
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .removalListener(MY_LISTENER)
        .build(
        new CacheLoader<Key, Value>() {
            public Value load(Key key) throws Exception {
                return createExpensiveValue(key);
            }
        });
    //...
    try {
       cache.get(key);
    } catch (ExecutionException e){
      throw new OtherException(e.getCause());
    }
    

    使用 Callable

    当没有默认加载运算,或者想要覆盖默认的加载运算,同时保留 “获取缓存 -- 如果没有 -- 则计算”(get-if-absent-compute)的原子语义时使用该方式。示例如下:

    Cache<Key, Value> cache =  CacheBuilder.newBuilder()
        .expireAfterWrite(1,TimeUnit.MINUTES)
        .removalListener(this)
        .build();
    //...
    // 1. get
    try {
      cache.get(key, new Callable<Value>() {
        @Override
        public Value call() throws AnyException {
          return doThingsTheHardWay(key);
        }
      });
    } catch (ExecutionException e) {
      throw new OtherException(e.getCause());
    }
    
    // 2. getIfPresent
    cache.getIfPresent(key);
    

    参考

    1. CachesExplained - guava
    2. [Google Guava] 3-缓存 - 并发编程网
    写在后面:

    1. 子曰:「学而不思则罔,思而不学则殆」。
    2. 站点地图
    2. 本作品作者为 Lshare,采用知识共享署名 4.0 国际许可协议进行许可。
  • 相关阅读:
    12.数组三--数组的冒泡排序与快速排序
    11.数组二
    10.数组一
    Vue之组件与父子传值
    Django模型层
    面向对象的组合用法
    面向对象初识
    Python内置函数
    列表推导式,生成器表达式
    装饰器进阶
  • 原文地址:https://www.cnblogs.com/lshare/p/11334430.html
Copyright © 2011-2022 走看看