Search code examples
java

Is there any perofrmance difference between using TimeUnit.SECOND and TimeUnit.MILISECONDS when scheduling via ScheduledExecutorsService?


Is there any performance impact between scheduling tasks with milliseconds instead of seconds when using ScheduledExecutorsService?

For example:

ScheduledExecutorService executorService=Executors.newScheduledThreadPool(2);

executorService.schedule(new MyTask(),5000,TimeUnit.MILLISECONDS);
executorService.schedule(new MyTask(),5,TimeUnit.SECONDS); 

Real case scenario will be scheduling indeed in seconds (tenths of) but I would like to use milliseconds because of unit testing where I could set it for eg 100 ms.


Solution

  • ScheduledThreadPoolExecutor calls TimeUnit.toNanos:

    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay,
                                       TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture<?> t = decorateTask(command,
            new ScheduledFutureTask<Void>(command, null,
                                          triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }
    
    private long triggerTime(long delay, TimeUnit unit) {
        return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));
    }
    

    Which for seconds/milliseconds, do the exact same operations, just with different constants:

    • Seconds -> Nanos: { return x(d, C3/C0, MAX/(C3/C0)); }
    • Milliseconds -> Nanos: { return x(d, C2/C0, MAX/(C2/C0)); }

    So no performance difference, not even at a bytecode level, most likely.