I have a case where a thread can finish in 3 ways:
1) when someCondition is not satisfied;
2) when some error happens in the connection call (XmppException, NoResponseException or NotConnectedException);
3) when I interrupt the thread (thread.interrupt()).
See the code.
while (someCondition()) {
// create iq packet
// ...
try {
result = connection.createPacketCollectorAndSend(iq).nextResultOrThrow();
// process result
// ...
// check if the thread was interrupted
if (Thread.interrupted()) {
throw new InterruptedException();
}
} catch (Exception e) {
// cancel the task
return;
}
}
Sometimes my code doesn't know that the thread was interrupted (case 3): if the PacketCollector is waiting for the queue.pool() [see PacketCollector.nextResult(timeout)], the InterruptedException is caught by the loop in nextResult() and my thread.interrupt() call is ignored. IOW, my thread doesn't finish as I desired.
I think that if the PacketCollector calls an interruptible method (resultQueue.poll), it should throw the InterruptException so that the user can handle it. Furthermore, it should have methods called as "nextResultUninterruptibly" for cases where the user only cares with the timeout (NoResponseException).