简体   繁体   English

Java Collection实现了元素的超时

[英]Java Collection implementaiton with timeout of the elements

Is there some collection implementation supporting expiration of the elements. 是否有一些集合实现支持元素到期。

For example: 例如:

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

where 哪里

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

And after given time ( 10000ms in this particular example), added elements will be removed from the collection. 在给定时间(在此特定示例中为10000ms )之后,将从集合中移除添加的元素。 By using this, we will prevent overflow of our cachedUsers collection. 通过使用它,我们将防止我们的cachedUsers集合溢出。

Yes, Guava supports a cache with timed expiration. 是的,Guava支持具有定时到期的缓存。 See Guava Explained's page on caches . 请参阅Guava Explained的缓存页面

An alternative is an LRU (least-recently used) cache that disposes of the oldest accessed element when a new element is inserted. 另一种方法是LRU(最近最少使用)缓存,在插入新元素时处理最旧的访问元素。

目前还不清楚你是如何尝试使用该系列的,但是Guava的CacheBuilder可能对你有所帮助。

Another alternative is ExpiringMap : 另一种选择是ExpiringMap

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

You could implement this by writing a wrapper for, say, a TreeMap where you let the insertion time be the key. 你可以通过为TreeMap编写一个包装器来实现这一点,你可以将插入时间作为关键。 On each insert, you could drop the head list which has "timed out". 在每个插入上,您可以删除已经“超时”的头列表。

Using insertion time as an indication on whether or not in should be dropped seems like a bad idea though. 使用插入时间作为是否应该丢弃的指示似乎是一个坏主意。 It seems better to go with some LRU (least recently used) cache for instance. 例如,最好使用一些LRU(最近最少使用的)缓存。 Such caches are readily available in libraries such as EHCache for instance. 例如,在诸如EHCache的库中可以容易地获得这样的高速缓存。 Don't reinvent the wheel. 不要重新发明轮子。

Related questions: 相关问题:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM