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. }  

 

相關文章
相關標籤/搜索