Search code examples
javamultithreadingcustomizationexecutors

How to dynamically resize a cached threadpool in java


I'm doing asynchronous threading using futures in my work at the moment. I want its functionality to be similar to a 'cachedThreadPool' but also to do these two things:

  1. Increment the maximum number of threads allowed each time a thread successfully completes.

  2. Decrement the maximum number of threads allowed if a thread throws an exception or timeouts.

Is this possible to do in a custom ThreadPoolExecutor? I am new to using Executors in this way so pointing me in the right direction would be very helpful towards solving this.


Solution

  • Dynamically resizing thread pools should be considered carefully. If you have timeouts and your response is to reduce the number of threads, assuming the task is parrelizable, it will likely make the problem worse.

    Anyway, here's code that changes the size of the pool when a task throws an exception and makes it larger if a task completes succesfully

    class ManagedThreadPoolExecutor extends ThreadPoolExecutor {
          @Override
          protected void afterExecute(Runnable r, Throwable t) {
               if(t != null)
                    setMaximumPoolSize(getMaximumPoolSize()-1);
               else
                    setMaximumPoolSize(getMaximumPoolSize()+1);
    
          }
    }