FutureTask.cancel() - can anyone explain the mechanism?
Hi,
I have a class which implements Callable<Integer> which is submitted
to an ExecutorService
two methods of interest are as follows
// Called from producer thread.
public void addMessage(final String message) {
try {
blockingQueue.put(message);
}
catch (InterruptedException ie) {
// Log exception
}
}
// Implement Callable<Integer>
// Consume messages from blocking queue
public Integer call() {
try {
while (true) {
final String message = blockingQueue.take();
}
}
catch (Throwable t) {
// log Throwable
}
finally {
// Log that Thread has been cancelled/stopped
}
return 0;
}
When I submit the Callable to ExecutorService I receive a Future of
concrete class FutureTask.
If I invoke futureTask.cancel() I can see that I jump straight to the
finally clause of my call() method. No exceptions appear to be thrown.
Could someone explain to me
1. Why this happens.
2. If this is a safe mechanism for stopping my consumer thread.
3. If this is safe can I submit a Runnable instead of a callable and
safely cancel the Thread this way?
Many thanks for any help.