Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example shows a thread-safe variant of the SocketReader class that creates a Socket per thread, that is, the socket is not shared amongst multiple threads. This is a common scenario in server applications that must accept connections and requests and dispatch them to different handling threadsplace requests to several servers simultaneously, without using any locking.

Code Block
bgColor#FFcccc

// Thread-safe SocketReader
public class SocketReader implements Runnable {
  private final String host;
  private final int port;

  SocketReader(String host, int port) {
    this.host = host;
    this.port = port;
  }

  public void run() {
    Socket socket = null;
    try {
      socket = new Socket("somehost"host, 25port);
    } catch (UnknownHostException e) {
      // Forward to handler	
    } catch (IOException e) {
      // Forward to handler
    }
    // Do some useful work
  }
}

...

Code Block
bgColor#ccccff
class SocketReader implements Runnable {
  private static ThreadLocal<Socket> connectionHolder = new ThreadLocal<Socket>() {
    Socket socket = null;
    @Override public Socket initialValue() {		
      try {
        socket = new Socket("somehostdefaultHost", 25"defaultPort");
      } catch (UnknownHostException e) {
        // Forward to handler	
      } catch (IOException e) {
        // Forward to handler
      }
      return socket;
    }
	
    @Override public void set(Socket sock) {
      if(sock == null) { // Shuts down socket when null value is passed 	
        try {
  	  socket.close();
        } catch (IOException e) {
 	  // Forward to handler	
        }
      } else {
        socket = sock; // Assigns Socket with caller specified hostname and port
      }
    }
  };

  public static Socket getSocketConnection() {
    return connectionHolder.get();
  }

  public static void shutdownSocket() { // Allows client to close socket anytime
    connectionHolder.set(null);
  }

  public void run() {
    Socket socket = getSocketConnection();
    // Do some useful work
  }
}

...