Running a limited number of threads in Spring Boot Service

I am currently developing a web application using spring loading and I have a service level issue.

I have a hard method on my service. If multiple users call this service, applications stop due to low memory. Therefore, I want to limit the number of parallel threads of this method. So far I have used synchronized for this method. But this will limit it to the 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. Any help would be appreciated.

+1
source share
1 answer

, - ( ), , . , 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();
    }
}
+1

Source: https://habr.com/ru/post/1677438/


All Articles