Java Socket - how to catch Exception of BufferedReader.readline()

Posted by Hasan Tahsin on Stack Overflow See other posts from Stack Overflow or by Hasan Tahsin
Published on 2012-11-28T05:01:58Z Indexed on 2012/11/28 5:03 UTC
Read the original article Hit count: 163

Filed under:
|
|

I have a Thread (let's say T1) which reads data from socket:

public void run() {
  while (running) {
    try {
      BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); 
      String input = reader.readLine();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

Another Thread (lets say T2) try to finish the program in one of its method. Therefore T2 does the following:

T1.running = false;
socket.close();

Here is this scenario for which i couldn't find a solution:

  • T1 is active and waiting for some input to read i.e. blocking.
  • context switching
  • T2 is active and sets running to false, closes the socket
  • context switching
  • because T1 was blocking and T2 closed the socket, T1 throws an Exception. What i want is to catch this SocketException. i can't put a try/catch(SocketException) in T1.run(). So how can i catch it in T1's running-method? If it's not possible to catch it in T1's running, then how can i catch it elsewhere?

PS: "Another question about the Thread Debugging"
Normally when i debug the code step by step, i lose the 'active running line' on a context switch. Let's say i'm in line 20 of T1, context switch happens, let's assume the program continues from the 30.line of T2, but the debugger does not go/show to the 30.line of T2, instead the 'active running line' vanishes. So i lose the control over the code. I use Eclipse for Java and Visual Studio for C#. So what is the best way to track the code while debugging on a context switch ?

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading