我目前正在使用 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/