Collection of Java implementation with timeout of elements

Is there some kind of collection implementation that supports the expiration of elements.

For example:

Collection<User> cachedUsers = new ExpirableList<User>(10000); 

Where

 public ExpirableList(final long timeout){...} 

And after a given time ( 10000ms in this particular example), the added items will be removed from the collection. Using this, we will prevent our cachedUsers collection from overflowing.

+7
source share
4 answers

Yes, Guava supports expiration cache. See the Guava Explained page on caches .

An alternative is the LRU (least recently used) cache, which has the oldest available item when a new item is inserted.

+9
source

It's not entirely clear how you are trying to use the collection, but Guava CacheBuilder can help you.

+3
source

You can implement this by writing a wrapper, such as TreeMap , where you give the insert time with a key. On each tab, you can reset the list of headers with a "timeout".

Using insertion time as an indicator of whether to discard or not seems like a bad idea. It seems better to go with some LRU (least used) cache, for example. Such caches are readily available in libraries such as EHCache . Do not reinvent the wheel.

Related questions:

+2
source

Another alternative is ExpiringMap :

 Map<String, User> users = ExpiringMap.builder() .expiration(10, TimeUnit.SECONDS) .build(); 
+2
source

All Articles