Hi,
This question is a followup on this one.
Essentially what I am doing is declaring a ThreadPoolExecutor
with just one thread. I am overriding the beforeExecute()
method to put a sleep so that each of my tasks are executed with some delay among themselves. This is basically to give away the CPU to other threads since my thread is kind of thrashing.
So the expected behavior is:
For each new task in the ThreadPoolExecutor
, it calls the before execute function before executing the task and hence it sleeps for say 20s before it executes the task.
However this is what I see:
For each new task submitted:
- It executes the task
- Calls the beforeExecute method
- sleeps for say 20s
- RE-EXECUTE the task!
The order of 1. & 2. is not the same all the time.
Here are my questions:
- It is appearing that a new thread comes in after/during sleeping and goes ahead and executes my task right away while the actual thread is sleeping.
So does theThreadPoolExecutor
spawn a new thread as soon as an existing thread sleeps [thinking that the thread is terminated]?? I tried to put the keepAliveTime > sleeptime ..so that in case the above assertion is true .. it atleast waits for more than sleep time to spawn a new thread ...[hoping in the mean time the sleeping thread would be awake and theThreadPoolExecutor
would dump the idea of spawning a new thread - Even if it does spawn a new thread and execute my task right away, why would the task be re-executed after the sleeping thread wakes up !! Shouldn't the task be taken out of task Queue before that ??
- Am I missing something here ? Any other way to debug this scenario ?
=> An alternative method I was thinking to do the desired task [and not solve the peoblem] was to wrap the runnable with one more runnable and sleep the outer runnable before calling the inner one.