javascheduleexecutor

How can I update executor time?


I am working on executorService in Java. If the time is not out, the executor delay should be updated and the older one should be deleted.

Duration timeFromLast = Duration.between(this.lastTime, LocalDateTime.now());
Duration check = Duration.ofMillis(100);
Duration durationTillCheck = check.minus(timeFromLast);
if(durationTillCheck.toMillis() < 0)
{
    if(!executor.isShutdown())
    {
        executor.shutdownNow();
        executor = Executors.newSingleThreadScheduledExecutor();
    }
    executor.schedule(Task, 100, TimeUnit.MILLISECONDS);
}

But sometime there is an error like "caused by ClosedByInterruptException". How can I properly do this task?


Solution

  • The ClosedByInterruptException happens when you interrupt a task that is blocked in an I/O request. In this case, it will be happening because you are calling shutdownNow on the executor. (Calling shutdownNow is specified to call Thread.interrupt() on all of the executor's worker threads that are still doing something.)

    So ...


    Given that you definitely do want the task to stop NOW ... the problem is not in the code that you have shown us. The problem is in the code of the Task which is not properly dealing with the consequences of interruption. But we can tell you how to fix the Task code without seeing it.