执行者提交后,Future是否立即为isDone()返回false? [英] Does a Future instantly return false for isDone() right after an executor submit()

查看:116
本文介绍了执行者提交后,Future是否立即为isDone()返回false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到有关 executor.submit()调用的未来状态的文档.

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

示例:

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();

问题是提交后立即调用 isDone()时返回的 Future< byte []> 对象是否返回false?

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

或者 futureState 也可能是 true ,这样提交的任务已在 boolean futureState = result.isDone(); 之前执行过>?

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

推荐答案

我想知道提交的行为是否为isDone()的false构造了一个Future

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

只需检查答案的来源即可.

Just check the source for the answer.

FutureTask 构造函数中,私有字段 state 设置为 NEW . isDone()方法返回 state!= NEW .因此,从创建对象的那一刻起, isDone()在理论上是错误的.

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;
}

当然,如阿列克谢的答案所述,如果您的 futureState 变量可能为true,任务在您提交和检查之间已经执行.

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.

这篇关于执行者提交后,Future是否立即为isDone()返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆