Callable tasks, Future results

A few learning notes based on P196 [[Java Threads]]. See also
http://bigblog.tanbin.com/2010/07/futurejava-designed-for.html
http://bigblog.tanbin.com/2009/05/callable-tasks-simple-thread-pool-set.html
http://bigblog.tanbin.com/2011/01/exception-passing-between-threads.html

Callable is an enhanced Runnable. Whenever possible, I’d design with Callable rather than Runnable. However, Callable doesn’t extend Runnable. For example, there’s no “new Thread(Callable)”.

Q: Does it make sense to implement both Runnable and Callable interfaces, so my class can be used in both contexts?
%%A: conceivable.

Q: Can this technique be used to convert existing Runnable designs to use Callable, assuming run() calls call()?
%%A: you might find it troublesome to get the task output (either result or exception) when you use the task object as a Runnable.

A Future object represents the result of a task. I feel it’s a window into that real world task in JVM. The (either real or symbolic) task is *stateful*.

I think of the “future” construct as a concept first. It represents a yet-to-complete async task. It could be ready when you read it. As such, I think it’s implemented using condVars.

FutureTask (like SwingWorker) is one of the implementations of Future interface.

Just as a Thread is a (rather imperfect) handle on a JVM thread, a Callable object with the corresponding FutureTask object are handles on the real world task.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s