guava refreshAfterWrite 的使用

对着背影说爱祢 提交于 2020-08-11 15:04:57

曾经有个面试官我我guava的exipre和reflush的区别

我只指定,expire在更新缓存时会阻塞住所有线程

好伤心

其实reflush只会阻塞住一个线程,然后其他线程获取到原先的值,这样就不会将所有线程都阻塞了,代码如下

package com.test;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Client {
    public static void main(String[] args) throws ExecutionException {
        Cache<String, String> cache = CacheBuilder.newBuilder()
//                .expireAfterWrite(7200 - 10, TimeUnit.SECONDS)
                .refreshAfterWrite(2, TimeUnit.SECONDS)
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(String key) throws Exception {
                        System.out.println(Thread.currentThread()+"reflush load ----");
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread()+"reflush get the val ----");

                        return LocalDateTime.now().toString();
                    }

                });


        ExecutorService pool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 3; i++) {
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        String val = null;
                        try {
                            val = ((LoadingCache<String, String>) cache).get("asd");
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread() + "main val:" + val);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
            });
        }




    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!