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


问题内容

我目前正在使用Spring Boot开发Web应用程序,并且服务层存在问题。

我在服务层上使用了繁重的方法。如果多个用户调用同一服务,则由于内存不足,应用程序将停止。所以我只想限制该方法的并行运行线程数。到目前为止,我已经在该方法上使用了
同步 。但是它将限制为单线程方法。

@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();
    }
}