我正在使用来自 google guava 的 ConcurrentHashMap
(通过 MapMaker),但该实现未排序。
google guava 中有 ConcurrentSkipListMap
,但该结构不会过期。
有没有什么结构可以同时做到这两点?
最佳答案
我会使用 ConcurrentSkipListMap
并定期迭代 map 以清除过期的内容。由于 skiplist 是无界的,这会导致内存泄漏的可能性,当驱逐线程无法 catch 时,但实际上这似乎非常非常不可能,除非你做了一些极端的事情。我也做过这样的事情,但我没有想使用后台线程:
static AtomicInteger cnt = new AtomicInteger();
Val put(K key, V val){
//Do the usual stuff
if(cnt.getAndIncrement() % 100 == 0){
//iterate map and evict stuff
}
}
if(cnt.getAndIncrement() % 100 == 0)
可能是一个“巧妙的优化”,所以也许您可以像 matt b 所建议的那样每次都进行迭代和逐出。
哦,当你这样做时,只有一个警告......当时间戳重合时,一定要打破不同实体之间的平等:
class Entity implaments Comparable<Entity>{
static AtomicInteger SEQ = new AtomicInteger();
int id = SEQ.getAndIncrement();
long timeStamp = System.currentTimeMillis();
int compareTo(Entity other){
// compare by timestamp
// If timestamps are equal, don't just return 0 yet!!
// Compare by id and return 0 ONLY IF the id equals.
// Otherwise entities disappear from your ordered map and
// it's really annoying to debug.
}
关于java - java中是否有并发&自过期&有序 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6146384/