Does a Future instantly return false for isDone() right after an executor submit()

Deadly 提交于 2019-12-11 04:12:15

问题


Could not find a documentation about the future state of an executor.submit() call.

Example:

byte[] b = new byte[ 4000000 ];
new Random().nextBytes( b );
Callable<byte[]> c = new SorterCallable( b );
ExecutorService executor = Executors.newCachedThreadPool();
Future<byte[]> result = executor.submit( c );
boolean futureState = result.isDone();

The question is if the returned Future<byte[]> object returns false when calling isDone() right after submit?

Or is it also possible that futureState is true such that the submitted task has been executed before boolean futureState = result.isDone(); ?


回答1:


I'm wondering if the very act of submitting constructs a Future with predefined false for isDone()

Just check the source for the answer.

In the FutureTask constructor, the private field state is set to NEW. The isDone() method returns state != NEW. Hence, the moment the object is created, isDone() is theoretically false.

public FutureTask(Runnable runnable, V result) {
    this.callable = Executors.callable(runnable, result);
    this.state = NEW;       // ensure visibility of callable
}

public boolean isDone() {
    return state != NEW;
}

Of course, as described in Alexey's answer, your futureState variable may be true if the task has executed between the time you submitted it and the time you checked.




回答2:


Answering the question

Or is it also possible that futureState is true such that the submitted task has been executed before boolean futureState = result.isDone(); ?

Technically yes, it is possible. Thread scheduling might go in such a way that task is completed at once. But, in most cases you will get false IMO.



来源:https://stackoverflow.com/questions/24385611/does-a-future-instantly-return-false-for-isdone-right-after-an-executor-submit

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