guava refreshAfterWrite 的使用

原创
07/21 10:30
阅读数 1.6K

曾经有个面试官我我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();
                        }

                    }
                }
            });
        }




    }
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部