Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added missing check

...

Code Block
bgColor#ccccff
class StopSocket extends Thread {
  protected Socket s;
  public void run() { 
    try {
      s = new Socket("somehost",25);
      BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
      String s = null;
        while((s = br.readLine()) != null) { 
          // blocks until end of stream (null)
        }
      System.out.println("Blocked, will not get executed until some data is received. " + s);
    }catch (IOException ie) { System.out.println("Performing cleanup"); }
    finally {
      System.out.println("Closing resources");
      try {
        if(s != null)
          s.close();
        } catch (IOException e) { e.printStackTrace(); }
    }
  }

  public void shutdown() throws IOException {
    if(s != null)
      s.close();
  }
}

class Controller {
  public static void main(String[] args) throws InterruptedException, IOException {
    StopSocket ss = new StopSocket();
    Thread t = new Thread(ss);
    t.start();
    Thread.sleep(1000); 
    ss.shutdown();
}
}

...