开发者

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

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&开发者_如何学Cgt; 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;


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜