在Spring Boot服务上运行有限数量的线程

我目前正在使用spring boot开发一个Web应用程序,我在服务层中遇到了问题。

我的服务层上有一个沉重的方法。 如果多个用户调用相同的服务,则应用程序会因内存不足而停止。 所以我想限制该方法的并行运行线程的数量。 到目前为止,我已经出现了在该方法上使用synchronized 。 但它会将它限制为单线程方法。

@Service public class DocumentService{ private synchronized void doReplacement(){ //should have limited no of multi threads (eg. 3) } private void normalMethod(){ //no restrictions } } 

我该怎么做才能完成这项任务。 任何帮助,将不胜感激。

使用某种请求限制(即每秒请求数)可能比使用同时执行方法的线程数更好。 例如,直接使用Guava的RateLimiter ,或者使用Spring的AOP添加声明性支持的事件。

如果您仍想使用线程,我的建议是使用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(); } }