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?
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 ...
If you don't want the exceptions, you shouldn't call shutdownNow
. Instead, call shutdown
and let the executor continue the current Task
until it is completed.
If you want the task to stop NOW, then call shutdownNow
as you are currently doing, and recode the Task
object so that it will cope with being interrupted. For instance, the Task
would need to deal with that exception ... in an appropriate way.
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.