原文地址:Guava庫學習:學習Guava Cache(七)RemovalListener(2)_RemovalListeners
html
接着上一篇Guava庫學習:學習Guava Cache(七)RemovalListener(1)_RemovalNotification,咱們繼續Guava Cache RemovalListener的學習,學習Guava Cache(七)RemovalListener(2)_RemovalListeners。java
RemovalListenersweb
RemovalListeners可以幫助咱們異步的處理,緩存條目移除後的通知,爲了讓咱們的Listener能夠在條目被移除時異步的處理通知,咱們能夠像下面這樣調用RemovalListeners. asynchronous方法:緩存
private ExecutorService executor; private ListeningExecutorService executorService; @Before public void setUp() { executor = Executors.newCachedThreadPool(); executorService = MoreExecutors.listeningDecorator(executor); } @Test public void testRemovalListener() { RemovalListener<String, TradeAccount> myRemovalListener = new RemovalListener<String, TradeAccount>() { @Override public void onRemoval(RemovalNotification<String, TradeAccount> notification) { //Do something here } }; RemovalListener<String, TradeAccount> removalListener = RemovalListeners.asynchronous(myRemovalListener, executorService); }
上面,咱們經過構造好的RemovalListener和executorService實例,並被它們做爲參數傳入 RemovalListeners.asynchronous的方法中。這個方法返回了一個RemovalListener實例,將異步的處理移除條目後的通知,這個步驟會發生在咱們將這個RemovalListener註冊到CacheBuilder實例後。
異步