I googled on this , but still could not get a solid understanding. I could not find any particular example that uses FutureTask(Runnable runnable, V result)
constructor
Java doc says
Future submit(Runnable task, T result)
Submits a Runnable task for execution and returns a Future representing that task. The Future's get method will return the given result upon successful completion.
Looking at this my understanding is upon task completion futureTask.get() it will send us back the given result object passed which has nothing to do with the "Runnable" job. This is kind of a signal that the "Runnable "job is completed.
Any concrete usecase or any real life example would be really helpful
Also in conjunction to Enno's answer how it is different from using isdone() possibly in a loop.
Edited
Also why not wait notify?
So, this is derived from a real-life use case, although it might not be representative of standard usage. Basically, I was adapting existing code that returned runnable.
LocalService manager = ...; // this is not thread safe
CompletionService exec = new ExecutorCompletionService( ... );
List<URL> work = ...;
for( URL url : work ) {
// this is existing code returning Runnable
Runnable task = createTaskFor(url);
exec.submit(task, url);
}
// we will report the URLs in the order they complete
for( int i = 0; i < work.size(); i++) {
URL completed = exec.take();
// manager isn't thread safe, so all calls to it are on this thread
manager.reportCompleted(completed);
}
So there you go. I only used it that one time. It was useful in combination with the CompletionService
, since that allows task production and task completion to be decoupled but still communcate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With