0

Suppose there is a thread pool running in a machine with 4 CPUs and I want do a load dynamic control to this pool. Could it be possible to change the corePoolSize when there are some threads running in the pool? That is, when the load is low, 2 threads at most are allowed to run simultaneously, but when the load is high, 4 threads are allowed. If not, is there a proper solution?

Xingjun Wang
  • 413
  • 2
  • 4
  • 17
  • 1
    "Most typically, core and maximum pool sizes are set only upon construction, but they may also be changed dynamically using setCorePoolSize(int) and setMaximumPoolSize(int)." From https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html – Fildor Jul 27 '16 at 14:25
  • How are you planning to detect high/low load? – Fildor Jul 27 '16 at 14:27
  • Re, "If not, is there a proper solution?" If it comes to the worst, nothing prevents you from implementing your own thread pool. – Solomon Slow Jul 27 '16 at 15:02
  • Thanks a lot for your comment. – Xingjun Wang Jul 28 '16 at 01:09

1 Answers1

1

Could it be possible to change the corePoolSize when there are some threads running in the pool?

Certainly. corePoolSize is marked as volatile in ThreadPoolExecutor so you can call tpe.setCorePoolSize(...) based on the load of your machine at any time. You could even spawn a job in your pool to sleep, check the load, and tweak the core pool size. You'd want to add another thread to the core size of course to do this.

That is, when the load is low, 2 threads at most are allowed to run simultaneously, but when the load is high, 4 threads are allowed.

This sounds fine although it is important to note that the only time this would actually make sense is if the jobs you are sending to the thread pool are completely CPU bound. Any IO (disk, network, etc.) would mean that reducing your concurrency wouldn't make much sense.

This said, I've never felt that I've had to do this although I've written a ton of threaded applications.

Gray
  • 115,027
  • 24
  • 293
  • 354