whether method cancel() and method interrupt() do the duplicate job?

我是研究僧i 提交于 2020-01-04 10:58:11

问题


I read the source of org.apache.nutch.parse.ParseUtil.runParser(Parser p, Content content).

Do these two method calls do the same thing:

Instruction 1:

t.interrupt();

Instruction 2:

task.cancel(true);

The source of the org.apache.nutch.parse.ParseUtil.runParser(Parser p, Content content) is:

ParseCallable pc = new ParseCallable(p, content);
FutureTask<ParseResult> task = new FutureTask<ParseResult>(pc);
ParseResult res = null;
Thread t = new Thread(task);
t.start();
try {
  res = task.get(MAX_PARSE_TIME, TimeUnit.SECONDS);
} catch (TimeoutException e) {
  LOG.warn("TIMEOUT parsing " + content.getUrl() + " with " + p);
} catch (Exception e) {
  task.cancel(true);
  res = null;
  t.interrupt();
} finally {
  t = null;
  pc = null;
}
return res;

回答1:


They don't usually do the same thing, as they act on different abstraction levels (tasks being a higher abstraction levels than threads). In this case, however the calls seem to be redundant.

FutureTask.cancel() tells the task that it no longer needs to run and (if true is passed as the argument) will attempt to interrupt the Thread on which the task is currently running (if any).

t.interrupt() attempts to interrupt the Thread t.

In this case it seems to be redundant. If the Task is still running, then cancel(true) should interrupt the thread, in which case the duplicate interrupt() call is unnecessary (unless the code running in the thread somehow ignores one interruption, but halts on two interrupts, which is unlikely).

If the Task is already complete at that point, then both cancel() and interrupt() will have no effet.




回答2:


Here,I'd like to make up a conclusion: when we pass the true as the argument of the FutureTask.cancel(),we can get the same effect as the interupt() does yet. why? Let's peek into the src of cancel() method. we got that the cancel() method call the method:

innerCancel(mayInterruptIfRunning);

when inside the method:innerCancel(mayInterruptIfRunning);,we can have the instructions below:

if (mayInterruptIfRunning) {
                Thread r = runner;
                if (r != null)
                    r.interrupt();
            }

So,in my case,the cancel() actually call the interrupt() indeed.



来源:https://stackoverflow.com/questions/7412491/whether-method-cancel-and-method-interrupt-do-the-duplicate-job

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!