【发布时间】:2021-03-13 15:23:06
【问题描述】:
最近我被要求(在一次采访中)设计HashMap 与每个键关联的 TTL。我使用下面给出的类似方法完成了它,但在他看来,这不是一个好方法,因为这需要在整个地图上进行迭代,如果地图大小以百万为单位,那么这将是一个瓶颈。
有没有更好的方法来做同样的事情?此外,他只关心线程在后台继续运行,尽管下一个 TTL 是几小时后。
class CleanerThread extends Thread {
@Override
public void run() {
System.out.println("Initiating Cleaner Thread..");
while (true) {
cleanMap();
try {
Thread.sleep(expiryInMillis / 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void cleanMap() {
long currentTime = new Date().getTime();
for (K key : timeMap.keySet()) {
if (currentTime > (timeMap.get(key) + expiryInMillis)) {
V value = remove(key);
timeMap.remove(key);
System.out.println("Removing : " + sdf.format(new Date()) + " : " + key + " : " + value);
}
}
}
}
【问题讨论】:
-
您可以使用 'timeQueue` 存储密钥、时间戳对,而不是
timeMap。继续删除密钥,直到找到超时密钥。您不必遍历其余的键。 -
他们要求你明确使用
Hashmap而不是LinkedHashMap?