So, let's say I have the following ScheduledExecutorService
:
public class Foo
{
private ScheduledExecutorService exec;
public Foo()
{
exec = Executors.newScheduledThreadPool(NUM_OF_TASKS);
}
public void executeOnce()
{
exec.schedule(new Runnable(){
@Override
public void run()
{
Foo.this.doSomething();
}}, DELAY, TimeUnit.MILLISECONDS);
}
}
Now, exec
is used to execute periodic tasks (e.g. directory polling, and etc). But, there's this one task (i.e. executeOnce
) that is executed once, but requires a delay. So, I chose to use exec
to execute this task, but is this good design? Instead, should I have created a newSingleThreadExecutor
, and then subsequently called shutdown
? For instance,
public void executeOnce()
{
// Execute task and wait 'til completion
ExecutorService exec = Executors.newSingleThreadExecutor();
try {
exec.submit(new Runnable(){
@Override
public void run()
{
try
{
Thread.sleep(DELAY);
} catch (InterruptedException e) {
}
Foo.this.doSomething()
}
}).get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
// Shutdown executor service
exec.shutdownNow();
}
Are there any benefits implementing the latter?
If the regular tasks and the one-time task are related in some way and the scheduling of the regular tasks is not as critical that a (possible) delay in their execution is a problem, then I'd simply execute the one-time task on the same executor.
The advantage of using a separate executor would be that the regular tasks are scheduled without interference. However shutdownNow()
would almost certainly not have the desired effect here, a simple shutdown()
would be more appropriate.