I search the database many times,even I have cache some result, it still cost took a long time.
List<Map<Long, Node>> aNodeMapList = new ArrayList<>();
Map<String, List<Map<String, Object>>> cacheRingMap=new ConcurrentHashMap<>();
for (Ring startRing : startRings) {
for (Ring endRing : endRings) {
Map<String, Object> nodeMapResult = getNodeMapResult(startRing, endRing,cacheRingMap);
Map<Long, Node> nodeMap = (Map<Long, Node>) nodeMapResult.get("nodeMap");
if (nodeMap.size() > 0) {
aNodeMapList.add(nodeMap);
}
}
}
getNodeMapResult is a function to search database according to startRing, endRing,and cache in cacheRingMap,and next time it may not need to search database if I find the result have exist in
cacheRingMap.
What I have tried:
My leader tell me that multithread technology can be used.So I change it to executorCompletionService,but now I have
a question,is this thread safe when I use concurrentHashMap to cache result in executorCompletionService?
Will it run fast after I change?
int totalThreadCount= startRings.size()*endRings.size();
ExecutorService threadPool2 = Executors.newFixedThreadPool(totalThreadCount>4?4:2);
CompletionService<Map<String, Object>> completionService = new ExecutorCompletionService<Map<String, Object>>(threadPool2);
for (Ring startRing : startRings) {
for (Ring endRing : endRings) {
completionService.submit(new Callable<Map<String, Object>>() {
@Override
public Map<String, Object> call() throws Exception {
return getNodeMapResult(startRing, endRing,cacheRingMap);
}
});
}
}
for(int i=0;i<totalThreadCount;i++){
Map<String, Object> nodeMapResult=completionService.take().get();
Map<Long, Node> nodeMap = (Map<Long, Node>) nodeMapResult.get("nodeMap");
if (nodeMap.size() > 0) {
aNodeMapList.add(nodeMap);
}
}