Spring @Async limit number of threads

夙愿已清 提交于 2019-11-26 23:12:25

问题


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


回答1:


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.




回答2:


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




回答3:


Since spring boot 2.1 you can use auto configuration and change the maximum number of threads in the application properties file

spring.task.execution.pool.max-size=4

See the full documentation:
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-task-execution-scheduling



来源:https://stackoverflow.com/questions/13206792/spring-async-limit-number-of-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!