英文:
Is there a way to understand why java.util.concurrent.Future is failed to cancel?
问题
我运行了一个应用程序,该应用程序安排在每隔X时间执行某些任务,为此我使用了ScheduledExecutorService
和java.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(() -> {DO SOMETHING} , 1000, 1000, MILLISECONDS);
if(doSomthing.cancel(!true)){
logger.warn("WHY FAILED");
}
答案1
得分: 0
java.util.concurrent.Future
.cancel() 如果任务已经完成、已被取消或由于其他某种原因无法取消,则取消操作将失败。如果成功,且在调用 cancel 时此任务尚未启动,则此任务不应当运行。如果任务已经启动,则 .cancel(true/false) 参数决定是否应中断执行此任务的线程以尝试停止任务。
如果你使用 (true),并且你的线程/{做某事} 被中断,你可以通过调用 doSomething.get() 来查看。它会抛出 InterruptedException、ExecutionException;因此,你应该用 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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论