有没有办法理解为什么 java.util.concurrent.Future 无法取消?

huangapple go评论59阅读模式
英文:

Is there a way to understand why java.util.concurrent.Future is failed to cancel?

问题

我运行了一个应用程序,该应用程序安排在每隔X时间执行某些任务,为此我使用了ScheduledExecutorServicejava.util.concurrent.Future
一切运行良好,但我想要在将来排查可能出现的问题,为此我想记录失败的原因。

示例:

private ScheduledExecutorService executeScheduler = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture doSomething = executeScheduler.scheduleAtFixedRate(() -> {DO SOMETHING}, 1000, 1000, MILLISECONDS);
if (doSomething.cancel(!true)) {
    logger.warn("为什么失败");
}
英文:

I ran an application which schedule to make some job every X time, for this mission I used ScheduledExecutorService and java.util.concurrent.Future. <br>
Everything work well but I want to troubleshoting possible issues in the future and for that I want to log the reason for failure. <br><br>

Example:<br>

private  ScheduledExecutorService executeScheduler = Executors.newSingleThreadScheduledExecutor();
private   ScheduledFuture doSomthing = executeScheduler.scheduleAtFixedRate(() -&gt; {DO SOMETHING} , 1000, 1000, MILLISECONDS);
if(doSomthing.cancel(!true)){
    logger.warn(&quot;WHY FAILED&quot;);
}

答案1

得分: 0

java.util.concurrent.Future
.cancel() 如果任务已经完成已被取消或由于其他某种原因无法取消则取消操作将失败如果成功且在调用 cancel 时此任务尚未启动则此任务不应当运行如果任务已经启动.cancel(true/false) 参数决定是否应中断执行此任务的线程以尝试停止任务

如果你使用 (true)并且你的线程/{做某事} 被中断你可以通过调用 doSomething.get() 来查看它会抛出 InterruptedExceptionExecutionException因此你应该用 try/catch 对其进行包装

注意.get() 会锁定并仅返回一个可抛出对象但在你的情况下很明显原因将是 InterruptedException或者也许你一开始就不想使用那个 .cancel

如果你尝试捕获一般的运行时异常你必须在线程的运行方法内部包装一个大的 try/catch或者就在这里
{做某事}
英文:

java.​util.​concurrent.​Future
.cancel() will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the .cancel(true/false) parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

in case that you use (true) and your thread/{DO SOMTHING} get interrupted you can see that by calling
doSomthing.get()
.It throws InterruptedException, ExecutionException;
so you should wrap it with try/catch.

note that .get() locks and return only a throwable. but in your case it will be obvious that the reason will be InterruptedException,
OR, maybe you didn't want to use that .cancel in the first place?

if you try to catch a general running exception you must wrap one big try/catch inside you thread run method or just here:
{DO SOMETHING}

huangapple
  • 本文由 发表于 2020年10月14日 14:43:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64347914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定