Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: renamed execute() to readData()

...

Code Block
bgColor#FFcccc
class SocketReader implements Runnable { // Thread-safe class
  private final Socket socket;
  private final BufferedReader in;
  private volatile boolean done = false;
  private final Object lock = new Object();

  public SocketReader() throws IOException {
    this.socket = new Socket("somehost", 25);
    this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
  }
  
  // Only one thread can use the socket at a particular time
  public void run() {
    try {
      synchronized (lock) {
        executereadData(); 
      }      
    } catch (IOException ie) {
      // Forward to handler
    }
  }

  public void executereadData() throws IOException {
    String string;
    while (!done && (string = in.readLine()) != null) {
      // Blocks until end of stream (null)
    }
  }

  public void shutdown() {
    done = true;
  }

  public static void main(String[] args) throws IOException, InterruptedException {
    SocketReader reader = new SocketReader();
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000);
    reader.shutdown();
  }
}

...

Code Block
bgColor#FFcccc
class SocketReader implements Runnable { // Thread-safe class
  // ...
  
  public void executereadData() throws IOException {
    String string;
    while (!Thread.interrupted() && (string = in.readLine()) != null) { 
      // Blocks until end of stream (null)
    }
  }
  
  public static void main(String[] args) throws IOException, InterruptedException {
    SocketReader reader = new SocketReader();
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000); 
    thread.interrupt();
  }
}

...

Code Block
bgColor#ccccff
class SocketReader implements Runnable {
  // ...
  
  public void executereadData() throws IOException {
    String string;
    try {
      while ((string = in.readLine()) != null) { 
        // Blocks until end of stream (null)
      }
    } finally {
      shutdown();
    }
  }
  
  public void shutdown() throws IOException {
    socket.close();
  }

  public static void main(String[] args) throws IOException, InterruptedException {
    SocketReader reader = new SocketReader();
    Thread thread = new Thread(reader);
    thread.start();
    Thread.sleep(1000); 
    reader.shutdown();
  }
}

...