Working of newSingleThreadScheduledExecutor, if thread already busy

前端 未结 1 965
清酒与你
清酒与你 2021-02-08 09:51

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\

1条回答
  •  我在风中等你
    2021-02-08 10:45

    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

    0 讨论(0)
提交回复
热议问题