Recently I was asked (in an interview) to design HashMap with TTL associated with each key. I done it using similar approach given below but as per him this is not a good approach as this would need iteration on whole map and if map size is in million then this would be a bottleneck.
Is there any better approach to do the same? Moreover- He was only concerned that a thread is kept running in background though the next TTL is hours later.
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);
}
}
}
}