Abhijit Mazumder
Abhijit Mazumder

Reputation: 9444

FutureTask with Runnable and Results

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?

Upvotes: 4

Views: 3858

Answers (2)

Darren Gilroy
Darren Gilroy

Reputation: 2121

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.

Upvotes: 3

Enno Shioji
Enno Shioji

Reputation: 26882

For example, you could do something like this:

Future<Article> article = 
    executor.submit(new PayForArticle(article.articleId), article);

showFunnyVideo();
playAlittleGame();

// ...OK let's actually show the user the article

Article article = article.get();

// The above will block until the article is payed for
// And throws exceptions if it failed

Edit:

How it different from `while (!futureTask.isdone) //sleep for sometime// //when done show article//

This is probably a different question but you should never do that because sleeping/checking/sleeping is less efficient than just calling get, and IMO is much clearer what you are trying to do.

Upvotes: 2

Related Questions