简体   繁体   中英

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)". 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 ()".

I have found that C ++ provides a "future:: valid" function to check if the value returned by "future:: get" is still valid. 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).

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?

Java is not C++. Future.get() is "valid" as long as you have a reference to said variable and won't get collected by the garbage collector.

Mind that Future.get() will block if the thread hasn't finished executing. If you need to check if the result is ready or not without blocking, Future provides the .isDone() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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