Use of FutureTask

I have a class which implements Runnable and has a separate method for returning a result (few different methods because you can get various results) .. there is also some stuff that has to be done when cancelling/interrupting the running of this.

Now, I've been asked to use FutureTask

This is where I am stuck. I've read the tutorials, searched Google, but I can't find information on how to use Runnable classes with FutureTask - especially where I need to do more than the standard FutureTask Cancel method and where in different circumstances have to return different result types.

I was also confused about the constructor

FutureTask(Runnable runnable, V result)

When I read the Java 1.5 code all this does is set the value of result to what is passed in the constructor... but how can that be when a result can't be set until you actually call runnable.run() method?

My first thought was to create a class which extends FutureTask and use the FutureTask(Runnable runnable, V result) constructor but then I can't figure out the rest.

[1089 byte] By [smiles78a] at [2007-11-27 5:16:25]
# 1

The Java API offers some nice tools since version 1.5 to work with Future.

As an example, you could use the following code:

ExecutorService executor = Executors.newSingleThreadExecutor();

Future future = executor.submit(myRunnableClass);

Future is the interface implemented by FutureTask so this should do the trick for you.

Dalzhima at 2007-7-12 10:39:02 > top of Java-index,Core,Core APIs...
# 2
I need to override future.cancel () method
smiles78a at 2007-7-12 10:39:02 > top of Java-index,Core,Core APIs...
# 3
What do you want to achieve by overriding cancel? Maybe you should use the Observer Pattern to perform your other "tasks" upon cancellation.
Dalzhima at 2007-7-12 10:39:02 > top of Java-index,Core,Core APIs...
# 4
To call methods of an object I am using to clean it up when the operation times out.I found a book that explains how to do it.
smiles78a at 2007-7-12 10:39:02 > top of Java-index,Core,Core APIs...
# 5

Calling cancel on a FutureTask will attempt to prevent it from starting, and if it has started, it will attempt to interrupt it if you are using cancel(true).

The Task being run won't end magically. When a Thread is interrupted, is simply sets a flag which should be periodically checked by the task using if(Thread.interrupted()).

Your FutureTask won't be cancellable unless you make it so. And by making it cancellable, you'll already be aware of when to perform your cleanup. There's no need to subclass FutureTask.

Dalzhima at 2007-7-12 10:39:02 > top of Java-index,Core,Core APIs...