Bookmark Topic Watch Topic
  • New Topic

Future class use in concurrent package with Runnable interface..  RSS feed

 
Rajat Jindal
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Report post to moderator
What is the exact use of Future class in java.util.concurrent package?
Can we use it for Runnable interface instead of Callable interface which does not return any value, if yes, how?
 
Rajat Jindal
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Report post to moderator
I can see following method in java.util.concurrent.ExecutorService class



Since java.util.Runnable interface has only run() method and which cannot return any value , what will be Future<?> object's use here and what value Future object will catch/wrap/store in it for Runnable interface?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
A Future represents the return value of a method that will be executed asynchronously, for example on another thread in an ExecutorService.

Let's suppose that in thread 1 you submit a task to an ExecutorService. When you submit the task to the ExecutorService, you get a Future object back. That ExecutorService is going to run the task on thread 2, but you don't know exactly when thread 2 is going to perform the task. At some point later, in thread 1, you need the result of the task. At that point you can call get() on the Future object. If the task has already executed, get() will immediately return the result. If not, then get() will make thread 1 wait until thread 2 has executed the task, and then it will return with the result.

A Runnable indeed does not return a value, so for a Runnable, a Future is not that useful. It's still useful in that case to find out if the asynchronous task has failed with a runtime exception (get() would throw an ExecutionException in that case), or if the task has been executed, which you can check with the isDone() method of Future.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Report post to moderator
This is a duplicate of http://www.coderanch.com/t/579977/threads/java/Future-object-Runnable-interface. Can you avoid posting the same question twice, please?

Both threads have an answer now, but the other is probably in a better forum so I'd suggest continuing discussion there.
 
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!