简体   繁体   English

如何知道 java.util.concurrent 未来接口是否仍然有效?

[英]How to know if java.util.concurrent Future Interface is still valid?

In my application I add a task to a "ScheduledThreadPoolExecutor" with the method "submit (Callable task)".在我的应用程序中,我使用“提交(可调用任务)”方法将任务添加到“ScheduledThreadPoolExecutor”。 The method returns a "Future" whose result I evaluate in another thread.该方法返回一个“未来”,我在另一个线程中评估其结果。 But this thread runs other code and it might take a while to execute "Future.get ()".但是这个线程运行其他代码,执行“Future.get()”可能需要一段时间。

I have found that C ++ provides a "future:: valid" function to check if the value returned by "future:: get" is still valid.我发现 C ++ 提供了一个“future::valid” function 来检查“future::get”返回的值是否仍然有效。 But Java provides neither a method nor an exception that indicates whether "Future.get ()" is no longer valid (in case the Garbage Collector has already removed the corresponding task from the "ScheduledThreadPoolExecutor" queue).但是 Java 既没有提供方法也没有提供表明“Future.get()”是否不再有效的异常(如果垃圾收集器已经从“ScheduledThreadPoolExecutor”队列中移除了相应的任务)。

What is recommended to do?建议做什么? Should I try to remove the rest of the tasks from the reading thread and make it just wait for "Future.get ()" as soon as possible?我是否应该尝试从读取线程中删除任务的 rest 并使其尽快等待“Future.get()”?

Java is not C++. Java 不是 C++。 Future.get() is "valid" as long as you have a reference to said variable and won't get collected by the garbage collector.只要您有对所述变量的引用并且不会被垃圾收集器收集, Future.get()就是“有效的”。

Mind that Future.get() will block if the thread hasn't finished executing.请注意,如果线程尚未完成执行, Future.get()将阻塞。 If you need to check if the result is ready or not without blocking, Future provides the .isDone() method.如果你需要在没有阻塞的情况下检查结果是否准备好, Future提供了.isDone()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM