在Spring Boot服务上运行有限数量的线程 [英] Run limited number of threads on Spring Boot service
问题描述
我目前正在使用spring boot开发一个Web应用程序,我在服务层遇到了问题。
I'm currently developing a web application using spring boot and I have a problem in the service layer.
我的服务层上有一个沉重的方法。如果多个用户调用相同的服务,则应用程序会因内存不足而停止。所以我想限制该方法的并行运行线程的数量。到目前为止,我已经开始在该方法上使用 synchronized 了。但它会将它限制为单线程方法。
I have a heavy method on my service layer. If multiple users call that same service, the applications stops due to low memory. So I want to limit the no of parallel running threads of that method only. So far I have come out with using synchronized on that method. But it will limit it to single threaded method.
@Service
public class DocumentService{
private synchronized void doReplacement(){
//should have limited no of multi threads (eg. 3)
}
private void normalMethod(){
//no restrictions
}
}
我能做什么?做到这一点。任何帮助将不胜感激。
What can I do to achieve this task. Any help would be appreciated.
推荐答案
您可能更善于使用某种请求限制(即每秒请求数) )与可以同时执行方法的线程数相比。例如直接使用 Guava的RateLimiter ,或者事件为Spring的AOP添加声明性支持。
You may be better of with using some sort of request throttling (i.e. number of requests per second) than with the number of threads that can execute a method simultaneously. For instance using Guava's RateLimiter directly, or maybe event adding declarative support for with Spring's AOP.
如果您仍想使用线程,我的建议是使用ExecutorService:
If you still want to go with threads, my suggestion would be to use an ExecutorService:
@Service
public class DocumentService {
private final ExecutorService executor;
@Autowired
public DocumentService(
@Value("${some.config.property}") int maxConcurrentThreads) {
// will allow only the given number of threads
executor = Executors.newFixedThreadPool(maxConcurrentThreads);
}
private void doReplacementWithLimitedConcurrency(String s, int i){
Future<?> future = executor.submit(() -> doReplacement(s, i));
future.get(); // will block until a thread picks up the task
// and finishes executing doReplacement
}
private void doReplacement(String s, int i){
}
// other methods
@PreDestroy
public void performThreadPoolCleanup() throws Exception {
executor.shutdown();
executor.awaitTermination(10, TimeUnit.SECONDS);
executor.shutdownNow();
}
}
这篇关于在Spring Boot服务上运行有限数量的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!