我将TimerDoc cancel()方法的语义与JavaDoc与实际行为和源代码进行比较时有些困惑。
JavaDoc谈到了返回值:
如果计划将任务安排一次执行并且已经运行,或者从未计划任务,或者如果任务已经取消,则返回false。
但是,如果任务尚未运行但可以运行,则查找代码可能会返回false。我在看java.util.Timer代码(mainLoop()方法):
TimerTask task;
boolean taskFired;
synchronized(queue) {
// Wait for queue to become non-empty
while (queue.isEmpty() && newTasksMayBeScheduled)
queue.wait();
if (queue.isEmpty())
break; // Queue is empty and will forever remain; die
// Queue nonempty; look at first evt and do the right thing
long currentTime, executionTime;
task = queue.getMin();
synchronized(task.lock) {
if (task.state == TimerTask.CANCELLED) {
queue.removeMin();
continue; // No action required, poll queue again
}
currentTime = System.currentTimeMillis();
executionTime = task.nextExecutionTime;
if (taskFired = (executionTime<=currentTime)) {
if (task.period == 0) { // Non-repeating, remove
queue.removeMin();
task.state = TimerTask.EXECUTED;
} else { // Repeating task, reschedule
queue.rescheduleMin(
task.period<0 ? currentTime - task.period
: executionTime + task.period);
}
}
}
if (!taskFired) // Task hasn't yet fired; wait
queue.wait(executionTime - currentTime);
}
if (taskFired) // Task fired; run it, holding no locks
task.run();
这似乎取消()可以很容易地前的最后一次正确的叫,如果因为TimerTask的取消()代码只是设置了任务状态显然不能与任务的同步运行() :
public boolean cancel() {
synchronized(lock) {
boolean result = (state == SCHEDULED);
state = CANCELLED;
return result;
}
}
因此,从我的角度来看,上述之后给出的JavaDoc中的“松散”定义确实很严格:
宽松地说,如果此方法阻止一个或多个计划的执行发生,则返回true。
因此,再次看起来像false一样,因为cancel()方法的结果可能意味着该任务没有执行,但是将被执行。
请确认我的想法或告诉我我错了。
谢谢!
您的理解是正确的,false
结果显然并不表示任务执行已完成,而是已经开始。
理解“任务已运行”一词的最古怪的方式是“事情已经到了使调用cancel
失败以阻止任务运行的地步”。并且,当您考虑它时,这就是呼叫者cancel()
感兴趣的信息。
因此,是的,我也同意“宽松”条款比“严格”条款更为严格。
请记住,此Javadoc是在Java平台开发的早期就编写的,并且其质量标准随着时间的推移而不断提高。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句