I'm using the ExecutorService
on a @EnableScheduling
class to submit multiple executions of the same method.
Basically, my configuration is:
@Component
@EnableScheduling
public class JobQueue {
@Autowired
private JobQueueService jobQueueService;
private Integer threadPoolSize = 5;
private ExecutorService executorService = Executors.newFixedThreadPool(threadPoolSize);
@Scheduled(fixedDelay = 20_000)
private void run() {
for (int i = 0; i <= threadPoolSize; i++) {
Runnable runnableTask = () -> {
jobQueueService.processPendingJobs();
};
executorService.submit(runnableTask);
// Also, tried with executorService.execute(runnableTask);
}
}
}
But, the JobQueueService.processPendingJobs()
is running only in single-thread executions, even when it is called multiple times with the for on my scheduled class.
Has Spring a different Autowired implementation for multi-threaded purposes?
I also tried instantiating a new service on for-of loop for each execution:
JobQueueService jobQueueService = new JobQueueService();
...[Runnable code chunk]
And at this time, it calls multiple thread executions, but loses Spring Application Context (Beans and other properties).
Do I have to provide a specific Bean implementation for my JobService to run it in multi-threaded contexts and still use it as an Autowired component?
The processPendingJobs()
is annotated with synchronized
keyword, is that wrong? If yes, why?
@Service
public class JobQueueService {
public synchronized void processPendingJobs() {
// Run logic
}
}