javascheduledexecutorservice

ScheduledExecutorService wait for task to complete


I am creating a new thread to check a folder for new files then sleeping for a defined period of time.

My preference would be to use the ScheduledExecutorService, however, I can't find any documentation to clarify if this waits for the currently running task to complete before starting a new one.

For example, in the following code;

Integer samplingInterval = 30;
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10);
executorService.scheduleAtFixedRate(new WatchAgent(agentInfo), 
                                    0, 
                                    samplingInterval, 
                                    TimeUnit.SECONDS);

If the run() of WatchAgent takes longer than 30 seconds, will a new agent be created before it finishes?

Secondly, if I create an instance of WatchAgent, can I keep using the same instance for each periodic run?


Solution

  • Per the javadoc of scheduleAtFixedRate:

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

    scheduleAtFixedRate by definition takes a single Runnable instance. There is no way for you to provide different instances for each invocation of run. So to answer your question, the same instance will always be used for each periodic run.