• Post Reply Bookmark Topic Watch Topic
  • New Topic

returning values with Runnable.run()  RSS feed

 
Dan Murphy
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I noticed the following method defined in ExecutorService



This implies to me that you can create a Runnable that returns a result and execute this Runnable (and obtain it's result) using the method above.
But how do you create a Runnable that returns a result when this interface contains only a single run() method with a void return type?
If someone could show a simple example, I'd really appreciate it.

Thanks in advance,
Dan
[ March 05, 2008: Message edited by: Dan Murphy ]
 
Henry Wong
author
Sheriff
Posts: 22857
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This implies to me that you can create a Runnable that returns a result and execute this Runnable (and obtain it's result) using the method above.
But how do you create a Runnable that returns a result when this interface contains only a single run() method with a void return type?
If someone could show a simple example, I'd really appreciate it.


Did you read the JavaDoc completely? The object that will be returned is the object that is passed to the submit() method. The future object will just wait until the run() method is done and return the result object that it already has. The run() method doesn't generate or return the result object.

Now, to answer your question. Ideally, this resultant object is mutable. And the run() method will be passed a copy of this object. Either via a constructor (of the runnable object), or via a global variable. Once a result is calculated, the run() method just stores the result in the resultant object and return. The future object will then return this shared object via the get() method.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!