对于Hashtable的超时机制机制、Hashtable

由网友(尽揽少女心)分享简介:我有一个哈希表,根据交通繁忙。我想补充超时机制对哈希表,删除太旧记录。我的担心是,- 它应该是轻量级- 删除操作都有时间要求不严格。我的意思是(超时值是1小时)删除操作可以是1小时和1小时15分钟之后,。没有问题。 I have a hashtable that under heavy-traffic. I want...

我有一个哈希表,根据交通繁忙。我想补充超时机制对哈希表,删除太旧记录。我的担心是, - 它应该是轻量级 - 删除操作都有时间要求不严格。我的意思是(超时值是1小时)删除操作可以是1小时和1小时15分钟之后,。没有问题。

I have a hashtable that under heavy-traffic. I want to add timeout mechanism to hashtable, remove too old records. My concerns are, - It should be lightweight - Remove operation has not time critical. I mean (timeout value is 1 hour) remove operation can be after 1 hour or and 1 hour 15 minute. There is no problem.

我的看法是, 我创建了一个大阵列(如环形缓冲区),那家商店把时间和哈希表的关键, 当添加到哈希表,使用数组索引找到阵列把时间下一个插槽,   如果阵列插槽空,把插入时间和HT关键,   如果阵列插槽不为空,比较插入时间超时发生。      如果发生超时从哈希表中删除(如果尚未移除)      它没有超时发生,增量索引,直到找到空槽或timeouted阵列插槽。 从哈希表中移除当有大的阵列上没有运行。

My opinion is, I create a big array (as ring buffer)that store put time and hashtable key, When adding to hashtable, using array index find a next slot on array put time, if array slot empty, put insertion time and HT key, if array slot is not empty, compare insertion time for timeout occured. if timeout occured remove from Hashtable (if not removed yet) it not timeout occured, increment index till to find empty slot or timeouted array slot. When removing from hashtable there is no operation on big array.

不久,对于每一个添加操作哈希表,可从哈希表中删除1 timeouted元素或者什么也不做。

Shortly, for every add operation to Hashtable, may remove 1 timeouted element from hashtable or do nothing.

你是什么的更优雅,更轻量级的解决方案?

What is your the more elegant and more lightweight solution ?

感谢您的帮助,

推荐答案

您应该考虑而使用的 的LinkedHashMap 或者一个的 的WeakHashMap

You should rather consider using a LinkedHashMap or maybe a WeakHashMap.

,前者具有构造设置其元素的最后一次访问顺序的迭代顺序;这使得它琐碎删除太旧的元素。而其 removeEldestEntry 方法可以覆盖定义自己的政策时的一个新的插入后自动删除旧的条目。

The former has a constructor to set the iteration order of its elements to the order of last access; this makes it trivial to remove too old elements. And its removeEldestEntry method can be overridden to define your own policy on when to remove the eldest entry automatically after the insertion of a new one.

后者用于密钥弱引用,所以它有它可以自动垃圾回收没有其他的参考。任意键

The latter uses weak references to keys, so any key which has no other reference to it can be automatically garbage collected.

阅读全文

相关推荐

最新文章