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

标签 java spring multithreading spring-mvc 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's RateLimiter直接,或者事件 adding declarative support for with Spring's 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();
    }
}

关于java - 在 Spring Boot 服务上运行有限数量的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38475758/

相关文章:

Java native 查询 - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

java - 如何使用java在Repository Spring Boot中执行将由特定符号分隔的查询

java - Spring集成+Spring AMQP : How can I passing MessageProperties to int:service-activator?

c# - STA 线程中止异常

java - 服务器多线程一次仅应答一个客户端

Java - Thread - Sun 教程之一中的问题

java - 如何减少 Full GC 的数量?

java - 通过 Java 以 headless 模式运行 Appium

java - 在程序开始时从 .txt 文件将文件读入 ArrayList

java - 理解Spring AOP