Future.cancel()

M

Matthias Kaeppler

Hi,

I was wondering if this method, as implemented by e.g. the FutureTask
class, allows me to terminate a thread?
I created an ExecutorService and submit()-ed a Future object, which I
initialized with another object implementing runnable. The thread is
started correctly, but calling cancel() on this future object doesn't
seem to have any effect (although it returns true, indicating that
cancellation of the task succeeded).

How come?
 
T

Thomas Weidenfeller

Matthias said:
I was wondering if this method, as implemented by e.g. the FutureTask
class, allows me to terminate a thread?

No, you expect miracles. The concurrency classes are implemented in Java
and can't do more than you could do in own code. You will notice that
the API documentation talks about an *attempt* (not a guarantee) to
cancel the *task* (not the thread). After a call to cancel() the task
will claim to have been canceled - even if there is still processing
going on in the background. cancel() will, if permitted, try to
interrupt the underlying thread. It depends on the code in the thread
what happens there.

I created an ExecutorService and submit()-ed a Future object, which I
initialized with another object implementing runnable. The thread is
started correctly, but calling cancel() on this future object doesn't
seem to have any effect (although it returns true, indicating that
cancellation of the task succeeded).

It has the desired effect: Stating that you are no longer interested in
the result from the Future. Nothing more. As a courtesy, cancel()
informs the backend to stop trying to calculate the result (it is only
an *attempt*), but the backend is free to run to an end and produce a
result - a result which will then be discarded by the Future, because
you told it you no longer need it.
How come?

No miracles.

/Thomas
 
I

iksrazal

The way I've done it is by scheduling a TimerTask to to cancel the
task, overload done() and perform the operation if isCancelled returns
true. I got the idea from the concurrency-interest list where the
subject comes up occasionally.

HTH,
iksrazal
http://www.braziloutsource.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top