这个想法是在持久逻辑触发时将当前状态放在一边,同时将新输入引导到新存储中。这是此任务的基本模式:
class PeriodicPersist{
// Map must be volatile, persist may look at a stale copy
private volatile Map<String, String> keyToResultMap = new HashMap<String, String>();
public void newResult(String key, String result) {
synchronized(keyToResultMap) { // Will not enter if in the beginning of persist
keyToResultMap.put(key,result);
}
}
public void persist(){
Map<String, String> tempMap;
synchronized (keyToResultMap) { // will not enter if a new result is being added just now.
if(keyToResultMap.size() == 0) {
return;
}
tempMap = keyToResultMap;
keyToResultMap = new HashMap<String, String>();
}
// download freshMap to the DB OUTSIDE the lock
}
}