views:

55

answers:

2

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?

+3  A: 

Call close on the socket input stream. You should be able to do that from another thread.

Tom Hawtin - tackline
+1  A: 

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. That shouldn't matter: InterruptedException does not require you to have a throws clause in the method declaration. I'm looking at the source for readObject right now and it doesn't 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). 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.

Bob Cross