title: Performance issue using Javas Object streams with Sockets
body: <p>I'm trying to do local IPC using Sockets and Object streams in Java however I'm seeing poor performance.</p>
  
  <p>I am testing the ping time of sending an object via an ObjectOutputStream to receiving a reply via an ObjectInputStream over a Socket.</p>
  
  <p>Here's the Requestor:</p>
  
  <pre><code>public SocketTest(){
  
      int iterations = 100;
      try {
          Socket socket = new Socket("localhost", 1212);
  
          ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); 
          ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream()); 
  
          double start = System.currentTimeMillis();
          for (int i = 0; i &lt; iterations; ++i) {
  
              Request request = new Request();
              objectOutputStream.writeObject(request);
  
              Response response = (Response)objectInputStream.readObject();
          }
          double finish = System.currentTimeMillis();
          System.out.println("Per ping: " + (finish - start) / iterations );
  
      } catch (Exception e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>Here's the responder:</p>
  
  <pre><code>public ServerSocketTest(){
  
      try {
  
          ServerSocket serverSocket = new ServerSocket(1212);
          Socket socket = serverSocket.accept();
  
          ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
          ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
  
          Request request = (Request)objectInputStream.readObject();
          while (request != null) {
  
              Response response = new Response();
              objectOutputStream.writeObject(response);
              request = (Request)objectInputStream.readObject();
          }
      } catch (Exception e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>The result I'm getting is:</p>
  
  <p><strong>Per ping: 80.35</strong></p>
  
  <p>80 msec is far to slow for local traffic.</p>
  
  <p>Request and Response classes are very small and their serialisation is fast.</p>
  
  <p>I have tried naively adding:</p>
  
  <pre><code>socket.setKeepAlive(true);  
  socket.setTcpNoDelay(true);
  </code></pre>
  
  <p>with little effect.</p>
  
  <p>performing a ping localhost:</p>
  
  <pre><code>64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=0 ttl=64 time=0.035 ms  
  64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=1 ttl=64 time=0.037 ms  
  64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=2 ttl=64 time=0.049 ms  
  64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=3 ttl=64 time=0.039 ms  
  64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=4 ttl=64 time=0.056 ms  
  </code></pre>
  
  <p>is also fast.</p>
  
  <p>Java version 1.6.0_05l
  Running on RedHat 2.4</p>