曾经有个面试官我我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();
}
}
}
});
}
}
}
来源:oschina
链接:https://my.oschina.net/u/3574106/blog/4411646