Use of guava refreshAfterWrite

There was once an interviewer, the difference between exipre and reflush of my guava

All I know is that expire blocks all threads when updating the cache

so sad

In fact, reflush only blocks one thread, and then other threads get the original value, so that all threads will not be blocked, the code is as follows

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();
                        }

                    }
                }
            });
        }




    }
}

 

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324030055&siteId=291194637