Search code examples
javamultithreadingexecutorsscheduledexecutorservice

Use executer framework or normal thread?


Recently I got a interview question that:

There is a scenario where one thread executing batch operation in interval of one hour will you use executer framework or normal thread and why ?

I am confused .

As there is only one thread, there is no need of executors service. I can do it using while and sleep.

while(1)
{
// do task
// t1.sleep(60*60*1000);
}

While there is a ScheduleExecutorService which provides so many methods for scheduulling?

What is the best way?


Solution

  • The problem with your solution above is that if your task takes 59mins, then your thread will spend 59mins executing your task, then sleep for an hour. So you'll invoke your task once every (nearly) 2 hours.

    If you use the scheduled executor framework, then that'll look after invoking your task every hour on the hour (regardless of how long it takes). Note also that it can handle the scenario in which your task executes for longer than one hour (either by design, or by accident). You can optionally opt to launch a second task in parallel, or skip the subsequent invocation.

    I would generally make use of the executor framework. It provides a lot of useful functionality, and you can encapsulate your tasks such that they don't just have to be run in a scheduled executor, but any executor.