原文地址:Guava库学习:学习Guava Cache(七)RemovalListener(2)_RemovalListeners
接着上一篇Guava库学习:学习Guava Cache(七)RemovalListener(1)_RemovalNotification,我们继续Guava Cache RemovalListener的学习,学习Guava Cache(七)RemovalListener(2)_RemovalListeners。
RemovalListeners
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实例后。
来源:oschina
链接:https://my.oschina.net/u/615599/blog/358870