Skip to content Skip to sidebar Skip to footer

Working Of Newsinglethreadscheduledexecutor, If Thread Already Busy

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: Sc

Solution 1:

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

Post a Comment for "Working Of Newsinglethreadscheduledexecutor, If Thread Already Busy"