Multithreading in spring Multithreading in spring multithreading multithreading

Multithreading in spring


  1. Main difference: in option 1) you create new executor on everyupdateRating() call, in option 2) executor is created once on deploymenttime, you feed the same single executor with new jobs. Second approach is much better.

  2. Why do you need to shut down the executor? Creating new executorsand shutting them down to wait until task is processed is antipattern. Remember, that executors are created in order to control system resources and should be treated such. (E. g. you have DB connection pool of 50 connections - so to serve DB access you create executor of 50 threads - to avoid connection limit exceed. Or you have 24 cores on server and need to parallelize work in the best possible way).

    And, as I mentioned in comment, in some environments (such as app servers) you often have no rights to shut down executor. Such attempt will produce SecurityException.

  3. If you need to wait until workers finish their jobs, wrap every job with Callable instead of Runnable, then from main thread call corresponding future.get() - and it will blockuntil job finishes. Timeouts are supported. Example

  4. Absolutely right. Threads are created and destroyed by executor itself, when it thinks is best time to. Try to monitor your app with jvisualvm to see how it happens.


1.) Option 1 is badly implemented since you define your executor service locally and close it after each use. This defeats the purpose of creating a thread pool - it needs to be a global object, so Option 2 is the way to go.

2.) You don't need to shut down the executor service when calling a web service. If the webservice does not respond the call will eventually time out and the thread fill complete execution. If you shut down the executor service, it won't be available for the next call.

3.) If you need some form of notifcation once your thread has finised, you should use Callable in conjuction with Futures instead.

4.) Your executor service has a maximum of 10 threads allocated, it won't spawn off more than those. If all of them are busy, you task will idle until one of those threads becomes available.