Created
December 13, 2018 13:52
-
-
Save YSMull/3fe3bc8c4b53efac9e71f51c59d19fb0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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