依賴java
com.google.guava:guava:20.0
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<String, Object> 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"; } }