My question is very similar to this one : @Async prevent a thread to continue until other thread have finished
Basically i need run ~ hundreds of computations in more threads. I want to run only some amount of parallel threads e.g. 5 threads with 5 computationis in paralell.
I am using spring framework and @Async option is natural choice. I do not need full-featured JMS queue, that`s a bit overhead for me.
Any ideas ? Thank you
Maximum number of threads in Spring Boot Application If you are using Tomcat as your embedded server (default), then you can use the property server. tomcat. max-threads to control how many threads you want to allow. This is set to 0 by default which means- use the Tomcat default which is 200 .
Simply put, annotating a method of a bean with @Async will make it execute in a separate thread. In other words, the caller will not wait for the completion of the called method. One interesting aspect in Spring is that the event support in the framework also has support for async processing if necessary.
The @EnableAsync annotation switches on Spring's ability to run @Async methods in a background thread pool. This class also customizes the Executor by defining a new bean. Here, the method is named taskExecutor , since this is the specific method name for which Spring searches.
Never use @Async on top of a private method. In runtime, it will not able to create a proxy and, therefore, not work.
If you are using Spring's Java-configuration, your config class needs to implements AsyncConfigurer
:
@Configuration @EnableAsync public class AppConfig implements AsyncConfigurer { [...] @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(5); executor.setQueueCapacity(50); executor.setThreadNamePrefix("MyExecutor-"); executor.initialize(); return executor; } }
See @EnableAsync
documentation for more details : http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html
Have you checked out Task Executor
? You can define a Thread Pool, with a maximum number of threads to execute your tasks.
If you want to use it with @Async
, use this in your spring-config:
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/> <task:executor id="myExecutor" pool-size="5"/> <task:scheduler id="myScheduler" pool-size="10"/>
Full reference here (25.5.3). Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With