java - 有生存时间的消息队列

标签 java collections message-queue java.util.concurrent

我寻找一个队列,该队列在特定时间(即 10 秒)内最多存储 N 个元素,或者如果已满则应处理最旧的值。

我在 Apache Collections (CircularFifoQueue JavaDoc) 中发现了一个类似的队列,它忽略了生存时间方面的问题。一个完整的消息代理似乎是我的小项目的开销。

你介意给我一个提示,我应该如何实现它吗?我是否应该在轮询元素时过滤掉旧值?

最佳答案

有一个类叫做LinkedHashMap它有一个特殊的方法来删除陈旧的数据。来自文档:

protected boolean removeEldestEntry(Map.Entry eldest)
Returns true if this map should remove its eldest entry.

方法removeEldestEntry 在任何时候被添加到列表(队列)时被调用。如果它返回 true 则删除最老的条目以为新条目腾出空间,否则什么也不会删除。您可以添加自己的实现,它会检查最老条目的时间戳,如果它早于到期阈值(例如 10 秒),则返回 true。所以你的实现可能看起来像这样:

protected boolean removeEldestEntry(Map.Entry eldest) {
    long currTimeMillis = System.currentTimeMillis();
    long entryTimeMillis = eldest.getValue().getTimeCreation();

    return (currTimeMillis - entryTimeMillis) > (1000*10*60); 
}

关于java - 有生存时间的消息队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37809326/

相关文章:

apache-kafka - 消费组的数量对Kafka性能有影响吗

python - 用 python 编写的 AMQP 代理?

javascript - Node.js 可以排队多少个事件?

java - 如何在 ListView 中仅显示一列数据?

java - 如果数据每次返回循环时都会被替换,如何将循环中的数据从最小到最大排序?

Scala 集合 : Using a value of Set find the key from a Map object.

vba - 使用 Collection.Add 用自定义对象填充 VBA 集合

java - 按钮对点击没有反应

java - 运行使用 Maven 构建的 jar 会导致 "java.lang.NoClassDefFoundError: org/rosuda/JRI/Rengine"错误

Java集合: Map getting updated while using fail-safe iterator