Stop a thread that does not interrupt

I have a stream that sits and reads objects outside 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 an InterruptedException and, as far as I can tell, no exception is thrown when this thread is interrupted. How to stop this thread?

+3
source share
3 answers

Call closein the socket input stream. You should be able to do this from another thread.

+3
source

It appears to clientSocketbe your only externally visible link. From another thread, callclientSocket.close()

ObjectInputStream IOException readObject(). catch .

, , readObject InterruptedException. : readObject, throws, InterruptedException.

catch (Exception ex) ( AKA), objectReadingThread.interrupt() ( , ). Javadoc:

wait(), wait (long), wait (long, int) Object, join(), join (long), join (long, int), sleep (long) sleep (long, int), , , InterruptedException.

- , , , ClosedByInterruptException.

, , , , .

, .

, , " - " , .

+2

InterruptedIOException. , , Java .

, , , IOException - , EOFException , . InterruptException, , : Exception. , -.

0

Source: https://habr.com/ru/post/1750150/


All Articles