Reputation: 7937
I have a thread which sends UDP packets at fixed intervals. After a while I am calling interrupt() from another thread and I am expecting the sender thread to completely finish after that. Most of the time, the sender thread does finish after receiving the interrupt. In some rare cases, however, the sender thread does not. Can you help me spot the mistake in my thread code?
try {
DatagramSocket socket = null;
Timber.d("Initialize the sender...");
while (!Thread.currentThread().isInterrupted()) {
try {
Timber.d("Sending UDP broadcasts...");
socket = new DatagramSocket();
while (!Thread.currentThread().isInterrupted()) {
String s = "hello";
byte[] buffer = s.getBytes();
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length,
mBroadcastAddress, PORT);
try {
if (BuildConfig.DEBUG)
Timber.d("[" + new DateTime().toLocalTime() + "] " +
"Send UDP packet");
socket.send(packet);
} catch (IOException ioe) {
Timber.d(ioe, "IOException");
}
Thread.sleep(TIMEOUT_SLEEP);
}
} catch (SocketException se) {
Timber.d(se, "Socket exception");
break;
} finally {
if (socket != null)
socket.close();
socket = null;
}
}
} catch (InterruptedException ie) {
Timber.d("The sender thread received interrupt request");
}
Timber.d("Finish the sender...");
Upvotes: 0
Views: 97
Reputation: 718798
I think that the problem is here:
} catch (IOException ioe) {
Timber.d(ioe, "IOException");
}
The problem is that one of the subtypes of IOException
is ... InterruptedIOException
. And when that exception is thrown (in response to an interrupt), the thread's interrupted
flag is cleared. Now it is "pretty unlikely" that this code is going to be interrupted in the middle of a send
call. But if it does, then you will effectively "eat" an interrupt.
I think you should change the above to:
} catch (InterruptedIOException ioe) {
Thread.currentThread().interrupt();
} catch (IOException ioe) {
Timber.d(ioe, "IOException");
}
In addition, if are going to test the interrupt flag later on, you are also "eating" it when you catch InterruptedException
at the end of the snippet, and you should set it again ... as above.
Upvotes: 1
Reputation: 752
As I can see, in a certain portion of your code, you are swallowing the interruptedException.Restore the interrupt after catching interruptedException,do not swallow it. This is how you restore the interrupt Thread.currentThread().interrupt();
Upvotes: 0