title: "java.net.BindException: Address already in use" when trying to do rapid Socket creation and destruction for load testing
body: <p>I'm trying to load test a Java server by opening a large number of socket connections to the server, authenticating, closing the connection, then repeating. My app runs great for awhile but eventually I get:</p>
  
  <blockquote>
    <p>java.net.BindException: Address already in use: connect</p>
  </blockquote>
  
  <p>According to documentation I read, the reason for this is that closed sockets still occupy the local address assigned to them for a period of time after close() was called. This is OS dependent but can be on the order of minutes. I tried calling <code>setReuseAddress(true)</code> on the socket with the hopes that its address would be reusable immediately after <code>close()</code> was called. Unfortunately this doesn't seem to be the case.</p>
  
  <p>My code for socket creation is:</p>
  
  <pre><code>Socket socket = new Socket();
  socket.setReuseAddress(true);
  socket.connect(new InetSocketAddress(m_host, m_port));
  </code></pre>
  
  <p>But I still get this error:</p>
  
  <blockquote>
    <p>java.net.BindException: Address already in use: connect after awhile. </p>
  </blockquote>
  
  <p>Is there any other way to accomplish what I'm trying to do? I would like to for instance: open 100 sockets, close them all, open 200 sockets, close them all, open 300, etc. up to a max of 2000 or so sockets.</p>
  
  <p>Any help would be greatly appreciated!</p>