guavagoogle-guava-cache

Is removalListener of guava cache runs in a separate thread?


I want to perform some cleaning when the object is removed from guava cache. But I need to do it after some time. Can I put sleep there? Will it block all threads? Or removalListener runs in a separate thread?

CacheBuilder.newBuilder().
.removalListener(notification -> {
    try {
        Thread.sleep(10 * 60 * 1000);
    } catch (InterruptedException e) {
    }
    try {
        //close
    } catch (final IOException e) {
    }
})
.build();

Solution

  • From Removal Listeners · CachesExplained · google/guava Wiki:

    Warning: removal listener operations are executed synchronously by default, and since cache maintenance is normally performed during normal cache operations, expensive removal listeners can slow down normal cache function! If you have an expensive removal listener, use RemovalListeners.asynchronous(RemovalListener, Executor) to decorate a RemovalListener to operate asynchronously.

    e.g.

    Executor executor = Executors.newFixedThreadPool(10);
    CacheBuilder.newBuilder()
            .removalListener(RemovalListeners.asynchronous(notification -> {
                Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MINUTES);
                try {
                    //close
                } catch (final IOException e) {
                }
            }, executor))
            .build();