Reputation: 18171
I have a thread that sits and reads objects off of an ObjectInputStream:
public void run() {
try {
ois = new ObjectInputStream(clientSocket.getInputStream());
Object o;
while ((o = ois.readObject()) != null) {
//do something with object
}
} catch (Exception ex) {
//Log exception
}
}
readObject does not throw InterruptedException and as far as I can tell, no exception is thrown when this thread is interrupted. How do I stop this thread?
Upvotes: 3
Views: 2116
Reputation: 22292
It appears that clientSocket
is your only externally visible reference. From another thread, call clientSocket.close()
That will force the ObjectInputStream
to throw the IOException on the readObject() call. That should trigger your catch block and get you out of the loop.
Re-reading your question, you say that readObject
doesn't throw InterruptedException. You're correct in that point: I'm looking at the source for readObject
right now and it neither throws
nor does it explicitly hide the InterruptedException
.
You should always be able to trigger that final catch (Exception ex)
block (AKA exception eater) by calling objectReadingThread.interrupt()
from another thread (or whatever you name your reading thread). Quoting the Javadoc:
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
If that isn't working, I would investigate that "do something with object" block and try to find the exception-eater that is consuming your interrupt and ignoring it.
Upvotes: 2
Reputation: 564
You can try to catch InterruptedIOException . I don't know if in your particular case it helps but it is a most clear Java way to deal with such cases.
I am dealing with a amazing case when despite catching of IOException in some magic way EOFException is uncaught, so I found your answer interesting as well. In another case there is a InterruptException despite it could not be : link to unexpected InterruptException. These cases have in common problems with exceptions handling close to I/O operations.
Upvotes: 0
Reputation: 147154
Call close
on the socket input stream. You should be able to do that from another thread.
Upvotes: 4