【发布时间】:2021-11-26 11:41:51
【问题描述】:
我正在尝试实现某种具有以下特征的地图。
应在生存时间过去后删除每个项目(除非生存时间为 0,然后该项目不会过期) get、put、remove、size 的平均复杂度都应该是 o(1)
我在构造函数中调用了一个线程,该线程进入 while(true) 循环并检查 ttl 是否已过期
线程的代码
class ttlWatchdog extends Thread {
@SneakyThrows
@Override
public void run() {
long timeToSleep ;
System.out.println("Initiating Cleaner Thread..");
while (true) {
timeToSleep = checkExpiredKeys();//need to change it to a diffrent
//System.out.println("thread will sleep for " + timeToSleep + "msc" );
Thread.sleep(timeToSleep);
}
}
public long checkExpiredKeys() throws BadParameterException {
// Just remove if timeToLive has been set before...
long timeToWake = 0;
long currentTime = System.currentTimeMillis();
int counter =0 ;
Set<Map.Entry<String, ObjectTimeStampPair> >s = valuesMap.entrySet().stream().filter(a-> a.getValue().getTtl()!=0).collect(Collectors.toSet());
for (Map.Entry<String, ObjectTimeStampPair> e : s) {
long timeItShouldRemove = e.getValue().getTtl();
if ((currentTime ) >= timeItShouldRemove) {
remove(e.getKey());
}else {// we need to take the minimum for the while loop everything here is bigger than current time i need to find the minumum
if (counter == 0 ){ // if it is the first element take it
timeToWake = e.getValue().getTtl();
counter ++;
}
else if (timeToWake > timeItShouldRemove){
timeToWake = timeItShouldRemove;
}
}
}
long result = timeToWake !=0 ? timeToWake -currentTime : 0 ;
//System.out.print("the time to wake is " + timeToWake + " the current time is " + currentTime + " and the result is " + result);
return result;
//
}
我的问题是 while(true) 效率不高,尤其是当地图为空或充满无限 ttl 的对象时。
【问题讨论】:
-
您好,欢迎来到 Stackoverflow! :-) 您注意到,使用 while(true) 可能效率低下。但你的实际问题是什么?您可以使用哪些其他技术来提高效率?
标签: java multithreading hashmap