85384

Run limited number of threads on Spring Boot service

Question:

I'm currently developing a web application using spring boot and I have a problem in the service layer.

I have a heavy method on my service layer. If multiple users call that same service, the applications stops due to low memory. So I want to limit the no of parallel running threads of that method only. So far I have come out with using <strong>synchronized</strong> on that method. But it will limit it to 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 task. Any help would be appreciated.

Answer1:

You may be better of with using some sort of request throttling (i.e. number of requests per second) than with the number of threads that can execute a method simultaneously. For instance using <a href="https://dzone.com/articles/ratelimiter-discovering-google" rel="nofollow">Guava's RateLimiter</a> directly, or maybe event <a href="https://www.javacodegeeks.com/2015/07/throttle-methods-with-spring-aop-and-guava-rate-limiter.html" rel="nofollow">adding declarative support for with Spring's AOP</a>.

If you still want to go with threads, my suggestion would be to use an 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(); } }

Recommend

  • Read properties file in Spring Boot
  • Spring boot 2.1 bean override vs. Primary
  • How should I handle async API calls using a CMS that does not allow async controller actions?
  • Error : “Transport endpoint is already connected”
  • How can I get a connected client's IP address?
  • Hibernate returning the values in session, but not from the database
  • How to use Spring WebClient to make multiple calls simultaneously?
  • Haskell Stack build specific executable
  • AWS S3 implementation for serving private files
  • Installing a python package in a desired folder
  • ImportError: cannot import name COMError in python
  • draw pie chart using iOS quartz 2D
  • Delphi. Analog of Memo/RichEdit
  • Where in the relevant specification is it documented that some comments in a SQL script are, in fact
  • Where to save the local DB created for iphone app?
  • Is it possible to create a self-extracting archive which will run a specific file when unzipped?
  • Reading XML into Datatable gives incorrect DateTime when the time has Time Zone info
  • segue from landscape only to portrait only
  • 'doc_del_count' bigger than 'doc_count' on CouchDB
  • Slicing an SPA into several components and use AngularJS
  • c# winform DrawToBitmap offscreen
  • Changing Jupyter Notebook start up folder by modifying “start in” not working any more
  • Find group of records that match multiple values
  • Sequential (transactional) API calls in angular 4 with state management
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • What is Eclipse's Declaration View used for?
  • Opengl-es onTouchEvents problem or a draw problem? [closed]
  • output of program is not same as passed argument
  • Javascript + PHP Encryption with pidCrypt
  • Redux, normalised entities and lodash merge
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Do create extension work in single-user mode in postgres?
  • WOWZA + RTMP + HTML5 Playback?
  • Getting Messege Twice Using IMvxMessenger
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • How can i traverse a binary tree from right to left in java?
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?