Guava库学习:学习Guava Cache(七)RemovalListener(2)

两盒软妹~` 提交于 2019-12-03 17:47:09

    原文地址: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实例后。


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!