import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class GuavaCache {
static Cache cache = CacheBuilder.newBuilder()
.expireAfterWrite(1000,TimeUnit.SECONDS)
.maximumSize(1000)
.build();
public static void main(String[] args) {
Runnable runnable = new Runnable(){
@Override
public void run() {
Object cacheVal=null;
try {
cacheVal = cache.get("a", GuavaCache::loadCache);
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("thread:"+Thread.currentThread()+",拿到了缓存值:"+cacheVal);
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
pool.execute(runnable);
}
System.out.println("thread:"+Thread.currentThread()+",is end");
}
static Object loadCache(){
System.out.println("开始耗时的缓存加载,thread:"+Thread.currentThread());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "cache hui val";
}
}