'Multi-threaded process using only one thread per execution [duplicate]
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
}
}
Solution 1:[1]
You can make the call to processPendingJobs() run in a new thread by annotating the method with Spring's @Async annotation. This annotation only works on public methods and they should always be called from another class. To enable asynchronous calling you also need to annotate a @Configuration annotated class with the @EnableAsync annotation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maurice |
