Guava Cache特性:refreshAfterWrite只阻塞回源线程,其余线程返回旧值

上一篇文章"Guava Cache特性:对于同一个key,只让一个请求回源load数据,其余线程阻塞等待结果"提到:若是缓存过时,刚好有多个线程读取同一个key的值,那么guava只容许一个线程去加载数据,其他线程阻塞。这虽然能够防止大量请求穿透缓存,可是效率低下。使用refreshAfterWrite能够作到:只阻塞加载数据的线程,其他线程返回旧数据。java

[java] view plain copy数据库

 在CODE上查看代码片派生到个人代码片

  1. package net.aty.guava;  
  2.   
  3. import com.google.common.base.Stopwatch;  
  4. import com.google.common.cache.CacheBuilder;  
  5. import com.google.common.cache.CacheLoader;  
  6. import com.google.common.cache.LoadingCache;  
  7.   
  8. import java.util.UUID;  
  9. import java.util.concurrent.Callable;  
  10. import java.util.concurrent.CountDownLatch;  
  11. import java.util.concurrent.TimeUnit;  
  12.   
  13.   
  14. public class Main {  
  15.   
  16.     // 模拟一个须要耗时2s的数据库查询任务  
  17.     private static Callable<String> callable = new Callable<String>() {  
  18.         @Override  
  19.         public String call() throws Exception {  
  20.             System.out.println("begin to mock query db...");  
  21.             Thread.sleep(2000);  
  22.             System.out.println("success to mock query db...");  
  23.             return UUID.randomUUID().toString();  
  24.         }  
  25.     };  
  26.   
  27.   
  28.     // 1s后刷新缓存  
  29.     private static LoadingCache<String, String> cache = CacheBuilder.newBuilder().refreshAfterWrite(1, TimeUnit.SECONDS)  
  30.             .build(new CacheLoader<String, String>() {  
  31.                 @Override  
  32.                 public String load(String key) throws Exception {  
  33.                     return callable.call();  
  34.                 }  
  35.             });  
  36.   
  37.     private static CountDownLatch latch = new CountDownLatch(1);  
  38.   
  39.   
  40.     public static void main(String[] args) throws Exception {  
  41.   
  42.         // 手动添加一条缓存数据,睡眠1.5s让其过时  
  43.         cache.put("name", "aty");  
  44.         Thread.sleep(1500);  
  45.   
  46.         for (int i = 0; i < 8; i++) {  
  47.             startThread(i);  
  48.         }  
  49.   
  50.         // 让线程运行  
  51.         latch.countDown();  
  52.   
  53.     }  
  54.   
  55.     private static void startThread(int id) {  
  56.         Thread t = new Thread(new Runnable() {  
  57.             @Override  
  58.             public void run() {  
  59.                 try {  
  60.                     System.out.println(Thread.currentThread().getName() + "...begin");  
  61.                     latch.await();  
  62.                     Stopwatch watch = Stopwatch.createStarted();  
  63.                     System.out.println(Thread.currentThread().getName() + "...value..." + cache.get("name"));  
  64.                     watch.stop();  
  65.                     System.out.println(Thread.currentThread().getName() + "...finish,cost time=" + watch.elapsed(TimeUnit.SECONDS));  
  66.                 } catch (Exception e) {  
  67.                     e.printStackTrace();  
  68.                 }  
  69.             }  
  70.         });  
  71.   
  72.         t.setName("Thread-" + id);  
  73.         t.start();  
  74.     }  
  75.   
  76.   
  77. }  

 

经过输出结果能够看出:当缓存数据过时的时候,真正去加载数据的线程会阻塞一段时间,其他线程立马返回过时的值,显然这种处理方式更符合实际的使用场景。缓存

 

 

有一点须要注意:咱们手动向缓存中添加了一条数据,并让其过时。若是没有这行代码,程序执行结果以下。app

因为缓存没有数据,致使一个线程去加载数据的时候,别的线程都阻塞了(由于没有旧值能够返回)。因此通常系统启动的时候,咱们须要将数据预先加载到缓存,否则就会出现这种状况。dom

 

还有一个问题不爽:真正加载数据的那个线程必定会阻塞,咱们但愿这个加载过程是异步的。这样就可让全部线程立马返回旧值,在后台刷新缓存数据。refreshAfterWrite默认的刷新是同步的,会在调用者的线程中执行。咱们能够改形成异步的,实现CacheLoader.reload()。异步

[java] view plain copyide

 在CODE上查看代码片派生到个人代码片

  1. package net.aty.guava;  
  2.   
  3. import com.google.common.base.Stopwatch;  
  4. import com.google.common.cache.CacheBuilder;  
  5. import com.google.common.cache.CacheLoader;  
  6. import com.google.common.cache.LoadingCache;  
  7. import com.google.common.util.concurrent.ListenableFuture;  
  8. import com.google.common.util.concurrent.ListeningExecutorService;  
  9. import com.google.common.util.concurrent.MoreExecutors;  
  10.   
  11. import java.util.UUID;  
  12. import java.util.concurrent.Callable;  
  13. import java.util.concurrent.CountDownLatch;  
  14. import java.util.concurrent.Executors;  
  15. import java.util.concurrent.TimeUnit;  
  16.   
  17.   
  18. public class Main {  
  19.   
  20.     // 模拟一个须要耗时2s的数据库查询任务  
  21.     private static Callable<String> callable = new Callable<String>() {  
  22.         @Override  
  23.         public String call() throws Exception {  
  24.             System.out.println("begin to mock query db...");  
  25.             Thread.sleep(2000);  
  26.             System.out.println("success to mock query db...");  
  27.             return UUID.randomUUID().toString();  
  28.         }  
  29.     };  
  30.   
  31.     // guava线程池,用来产生ListenableFuture  
  32.     private static ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));  
  33.   
  34.     private static LoadingCache<String, String> cache = CacheBuilder.newBuilder().refreshAfterWrite(1, TimeUnit.SECONDS)  
  35.             .build(new CacheLoader<String, String>() {  
  36.                 @Override  
  37.                 public String load(String key) throws Exception {  
  38.                     return callable.call();  
  39.                 }  
  40.   
  41.                 @Override  
  42.                 public ListenableFuture<String> reload(String key, String oldValue) throws Exception {  
  43.                     System.out.println("......后台线程池异步刷新:" + key);  
  44.                     return service.submit(callable);  
  45.                 }  
  46.             });  
  47.   
  48.     private static CountDownLatch latch = new CountDownLatch(1);  
  49.   
  50.   
  51.     public static void main(String[] args) throws Exception {  
  52.         cache.put("name", "aty");  
  53.         Thread.sleep(1500);  
  54.   
  55.         for (int i = 0; i < 8; i++) {  
  56.             startThread(i);  
  57.         }  
  58.   
  59.         // 让线程运行  
  60.         latch.countDown();  
  61.   
  62.     }  
  63.   
  64.     private static void startThread(int id) {  
  65.         Thread t = new Thread(new Runnable() {  
  66.             @Override  
  67.             public void run() {  
  68.                 try {  
  69.                     System.out.println(Thread.currentThread().getName() + "...begin");  
  70.                     latch.await();  
  71.                     Stopwatch watch = Stopwatch.createStarted();  
  72.                     System.out.println(Thread.currentThread().getName() + "...value..." + cache.get("name"));  
  73.                     watch.stop();  
  74.                     System.out.println(Thread.currentThread().getName() + "...finish,cost time=" + watch.elapsed(TimeUnit.SECONDS));  
  75.                 } catch (Exception e) {  
  76.                     e.printStackTrace();  
  77.                 }  
  78.             }  
  79.         });  
  80.   
  81.         t.setName("Thread-" + id);  
  82.         t.start();  
  83.     }  
  84.   
  85.   
  86. }  

 

相关文章
相关标签/搜索