How to use Guava Cache with expiry time for an ArrayList?

1.9k views Asked by At

I just found out about Guava Caching, and all the examples that I see are using map, key, and value.

Is there any way to use guava cache for an ArrayList?

I have an ArrayList that has elements, each element has 60 seconds to live, after that it should be removed, I appreciate any suggestions.

And is it possible to trigger a method after removal of each element? For example, if a number gets removed from the list I need to recalculate the average again.

1

There are 1 answers

2
syntagma On BEST ANSWER

Is there any way to use guava cache for an ArrayList?

Guava Cache is designed to be queried by key. However, you could use index of your ArrayList as a key or choose some unique property of the object to be the key (though as I understand, you need the values to be stored in the order they were added).

And is it possible to trigger a method after removal of each element?

Yes, when building your Cache<K, V>, set RemovalListener<K,V>.

For example:

Cache<String, String> cache = CacheBuilder.newBuilder()
    .expireAfterWrite(60, TimeUnit.SECONDS)
    .removalListener(new RemovalListener<String, String>() {
      public void onRemoval(RemovalNotification<String, String> removal) {
        // Compute the average here
      }          
    })
    .build();