Why is JPARepository.save method not working when used inside an ExecutorService task?
@Component
public class Testing {
@Inject
JobSummaryRepository jobSummaryRepository;
private Logger log = LoggerFactory.getLogger(JobSummary.class);
@PostConstruct
public void Save(){
JobSummary js = new JobSummary();
js.setCount(1L);
js.setCity_id(1L);
js.setCompany_id(1L);
js.setDate(new Date());
js.setJob_master_id(1L);
js.setHub_id(1L);
js.setUser_id(1L);
js.setJob_status_id(1L);
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<String> future = executor.submit(this.CallablecustomSaveOrUpdate(js));
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
} finally {
log.info("What!!");
}
//jobSummaryRepository.save(js);
executor.shutdown();
}
private Callable<String> CallablecustomSaveOrUpdate(JobSummary js){
return () -> {
jobSummaryRepository.save(js);
return "Done";
};
}
}
The code above doesn't throw any error nor saves any data in the database. Finally block is not executed as well.
On the other hand, commenting out ExecutorService logic and calling jobSummaryRepository.save(js) directly works perfectly fine.
I can't get my head around this.
I think @PostConstruct
is causing the problem. As it is called before all the spring component/context gets loaded.
You can use spring's ContextRefreshedEvent for this purpose.
Simple Example :
@Component
public Test implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//do something if all apps have initialised
}
}
Hope this will work.