When doing demand, you need to query some data from the department and conduct business verification of these data (whether to meet the conditions for order creation). This business verification is divided into three major pieces. At the time, this verification process will slow down, so I think of using multi -threaded to check. The following is the practice of code:
taskDetailList= xxxService.getXxxx();
if (taskDetailList==null || taskDetailList.size()==0){
return null;
}
final int nThreads = 10;
final int size = taskDetailList.size();
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
List< Future<DispatchCheckDto>> futures =
new ArrayList<Future<DispatchCheckDto>>(nThreads);
try {
for ( int i = 0; i < size; i++) {
final xxxxEntity subEntity = taskDetailList.get(i);
Callable<xxxDto> task = new Callable<xxxDto>() {
@Override
public DispatchCheckDto call() throws Exception {
return checkForThread(subEntity);
}
};
futures.add(executorService.submit(task));
}
for ( Future<xxxDto> future : futures) {
xxxDto fuDto = null;
try {
fuDto = future.get();
if(fuDto!= null&&StringUtils.isEmpty(fuDto.getFailReason())){
result.add(fuDto);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} finally {
executorService.shutdown();
}
long endTimde = System. currentTimeMillis();
LOGGER.info( "Multi -threaded checking information time consuming:" +(endTimde-startTime)+"ms, check number:" +size);
Look at the code above, which is different from the previous multi -threaded implementation (a multi -threaded before, usually writing a thread class or implementing the Runnable interface), ExecutorService is the new package method of JDK7, mainly in the class to achieve specific concrete in Callable Logic, using ExecutorService.Submit (task) for thread scheduling. In addition, it should be noted that the thread SHUTDOWN created by the ExecutorService in the Finally block is dropped.