jQuery in Action, 2nd edition
The moose likes Threads and Synchronization and the fly likes returning values with Runnable.run() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "returning values with Runnable.run()" Watch "returning values with Runnable.run()" New topic
Author

returning values with Runnable.run()

Dan Murphy
Ranch Hand

Joined: Mar 29, 2005
Posts: 126
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 ]

SCJP, SCJD, SCWCD
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16681
    
  19

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: returning values with Runnable.run()
 
Similar Threads
Doubt in reflection
some silly questions
How can a checked exception be thrown from run method of a thread ?
Interview Question
Type glitch caused by generics