Skip to content

Instantly share code, notes, and snippets.

@YSMull
Created December 13, 2018 13:52
Show Gist options
  • Save YSMull/3fe3bc8c4b53efac9e71f51c59d19fb0 to your computer and use it in GitHub Desktop.
Save YSMull/3fe3bc8c4b53efac9e71f51c59d19fb0 to your computer and use it in GitHub Desktop.
package com.netease.youdata.util;
import java.util.concurrent.ConcurrentHashMap;
public class ExpiredWindow<K, V> {
private Long windowSize;
private ConcurrentHashMap<K, V> dataMap = new ConcurrentHashMap<>();
private ConcurrentHashMap<K, Long> timeMap = new ConcurrentHashMap<>();
private Thread cleanupThread() {
return new Thread(() -> {
while (true) {
timeMap.forEach((k, remain) -> {
if (remain == 0) {
timeMap.remove(k);
dataMap.remove(k);
System.out.println("clean " + k);
} else {
timeMap.put(k, remain - 1);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "clean thread");
}
public V get(K key) {
return dataMap.getOrDefault(key, null);
}
public void put(K key, V value) {
dataMap.put(key, value);
timeMap.put(key, windowSize);
}
public ExpiredWindow(Long seconds) {
windowSize = seconds;
cleanupThread().start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment