How to interrupt BufferedReader's readLine

后端 未结 9 1386
醉梦人生
醉梦人生 2020-11-29 07:56

I am trying to read input from a socket line by line in multiple threads. How can I interrupt readLine() so that I can gracefully stop the thread that it\'s bl

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 08:22

    I was playing around with this recently (using Scala), and I didn't like the accepted answer of closing the socket and getting an exception.

    Eventually I discovered that it's possible to call socket.shutdownInput() in the interrupting thread to get out of the readLine call without an exception. I make this call in a SIGINT handler so that I can clean up and close the socket in the main thread.

    Note, that the equivalent exists for the outputstream with socket.shutdownOutput()

提交回复
热议问题