文章目录

有这么一个问题,我们在一个后台界面维护一个关键词的数据,期望当关键词发生变化时,能立即加载到java内存当中。如果变化过于频繁,则没有必要每次变更都 重新加载。一秒内最多加载一次即可。 这个工具类就是为了解决这个问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SpanRunner {

private final long span = 1000;
Map<Runnable, Long> timeMap = new ConcurrentHashMap<>();
Map<Runnable, Long> scheduleMap = new ConcurrentHashMap<>();

ScheduledExecutorService schedule = new ScheduledThreadPoolExecutor(1);

public void runSpan(Runnable runnable) {
if (!timeMap.containsKey(runnable)) {
timeMap.put(runnable, System.currentTimeMillis());
runnable.run();
} else {
if (!scheduleMap.containsKey(runnable)) {
long lastRun = timeMap.get(runnable);
if (System.currentTimeMillis() - lastRun > span) {

timeMap.put(runnable, System.currentTimeMillis());
runnable.run();
} else {
schedule.schedule(new Runnable() {
@Override public void run() {
timeMap.put(runnable, System.currentTimeMillis());

try {
runnable.run();
}catch (Exception e){
e.printStackTrace();
}finally {
scheduleMap.remove(runnable);
}
}
}, span, TimeUnit.MILLISECONDS);
scheduleMap.put(runnable, 1L);
}
}
}
}

}
文章目录