Home > Blockchain >  Will thread in thread pool (ThreadPoolTaskExecutor) be used for other tasks when in sleep?
Will thread in thread pool (ThreadPoolTaskExecutor) be used for other tasks when in sleep?

Time:07-20

I have a thread pool created from ThreadPoolTaskExecutor:

threadPoolTaskExecutor.setCorePoolSize(10);

this ThreadPoolTaskExecutor will execute runnables, each runnable has a Thread.sleep(6000); call during the task execution.

So when I execute the 1st task and when the 1st task calls Thread.sleep(6000) to sleep, at that time, execute the 2nd task, will it be possible the 2nd task will use the thread of the 1st task or interrupt the thread used by the 1st task? since it is in sleep.

CodePudding user response:

No, not automatically. If a normal Java Thread is sleeping, then it's sleeping.

Also, Threads are really cheap nowadays, I would not bother with details like that.

Working around the sleep and let that 'sleeping' Thread do some other work is really really hard to manage properly and easily will lead to loads and loads of unforeseen problems.

In your situation, what you COULD improve is that the pool size is not fixed but dynamic, releasing (destroying) threads when they haven't been used for some time (say: a minute). If more threads are needed, the pool will create new Threads, up to the given limit. (Executors.newCachedThreadPool()) That's especially helpful on a server, because 99% of threads on there are just idle (not even 'actively' sleeping).

Here are some details that might interest you: https://www.baeldung.com/thread-pool-java-and-guava

Especially check out ForkJoinPool: https://www.baeldung.com/java-fork-join, because this comes very close to a very similar problem.

  • Related