I'm trying to run a parallel tasks on a Spring Boot Project. I implement it by following this How to check that @Async call completed in Spring? But my code is not running it in parallel.
This is my config,
@Configuration
@EnableAsync
public class ThreadPoolExecutorConfig implements AsyncConfigurer {
@Bean(name = "ExportTaskExecutor")
public Executor executor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// TODO: research on what these config means and optimize it
executor.setCorePoolSize(2);
executor.setMaxPoolSize(4);
executor.setQueueCapacity(50);
executor.setThreadNamePrefix("AsynchThread::");
executor.initialize();
return executor;
}
}
Below is core to do my work,
@Service
public class ExportService {
public void call() throws JSchException, SftpException, IOException {
Integer threads = 10;
List<Future<List<ExportCsvModel>>> futures = new ArrayList<>();
//Run all threads
for (int i = 0; i < threads; i++) {
Integer limit = 5000;
Integer offset = i * limit;
futures.add(
this.processExportData(limit, offset)
);
}
List<ExportCsvModel> exportCsvModel = new ArrayList<ExportCsvModel>();
futures.forEach(result -> {
try {
exportCsvModel.addAll(result.get());
} catch (InterruptedException | ExecutionException e) {
log.info("ERROR:: " + e.getMessage());
}
});
//Export exportCsvModel to csv tasks
}
@Async("ExportTaskExecutor")
private Future<List<ExportCsvModel>> processExportData(Integer limit, Integer offset) throws IOException{
log.info("---->Running method ON OFFSET " + offset);
//Do a job
return new AsyncResult<List<ExportCsvModel>>(exportCsvModel);
}
}
The processExportData in for loop are not running in parallel. I will wait the previous to finish first. Do I miss something or is there anything I need to add ? Please help.