Search code examples
javaspringmultithreadingthreadpoolexecutor

New ThreadPoolExecutor for every request, or create a singleton spring bean of ThreadPoolExecutor


I have a Restful service that uploads images to S3 bucket. I was thinking of parallel uploads using ThreadPoolExecutor.

But should I create a global pool (like Spring singleton bean), or create a new ThreadPoolExecutor on every request?

Not sure if creating a bean is great idea as corePoolSize number of threads will always be alive in the application. Thanks, in advance.


Solution

  • You can try to create Spring @Bean like:

    @Bean
    public ExecutorService cachedThreadPool() {
       return Executors.newFixedThreadPool(5);
    }
    

    Or you can use the inner ThreadPoolExecutor. It all depends on your needs.