Home » Android » java – Working of newSingleThreadScheduledExecutor, if thread already busy

java – Working of newSingleThreadScheduledExecutor, if thread already busy

Posted by: admin June 15, 2020 Leave a comment

Questions:

My requirement is to make a service which keeps on checking a queue after specific interval & process the elements in queue.

For scheduling task after 10 seconds, I’m using:

ScheduledExecutorService schd = Executors.newSingleThreadScheduledExecutor();
schd.scheduleAtFixedRate(readQueueRunnable, 10, 10, TimeUnit.SECONDS);

My question is suppose first time, in queue there are many elements and my single thread starts processing the queue.

Even after 10 seconds my first thread is still executing it.

So when after 10 seconds, runnable is called again, will it stop the previous executing thread and start the new one.
Or, it will check if thread is already running & if it is running then it will skip going inside Runnable in that case.

How to&Answers:

newSingleThreadScheduledExecutor(); creates an executor with a single thread that will never do anything in parallel to the existing thread. It has just one and threads can’t execute more than 1 thing at a time.

If your tasks takes longer than 10 seconds, it will still create a new task after 10 seconds and put it in the queue of tasks that await completion. If tasks always take longer than the rate at which you schedule them you will get a constantly growing task queue and probably a memory related crash at some point.

So when after 10 seconds, runnable is called again, will it stop the previous executing thread and start the new one.

It will not stop anything. Executors re-use their thread. The threads executes all Runnable that you give to it in sequence. So it will simply execute the next runnable once the first is done.

Or, it will check if thread is already running & if it is running then it will skip going inside Runnable in that case.

It will not skip creating a task after 10 seconds.

The documentation explains it like

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

The “not concurrently” part is meant for executors that have multiple threads. Not relevant here since that can’t happen.


If you want that there is always a 10 second delay between tasks, use scheduleWithFixedDelay