title: How to prevent hangs on SocketInputStream.socketRead0 in Java?
body: <p>Performing millions of HTTP requests with different Java libraries gives me threads hanged on:</p>
  
  <p><code>java.net.SocketInputStream.socketRead0()</code></p>
  
  <p>Which is <code>native</code> function.</p>
  
  <p>I tried to set up Apche Http Client and <code>RequestConfig</code> to have timeouts on  (I hope) everythig that is possible but still, <strong>I have (probably infinite) hangs on <code>socketRead0</code>. How to get rid of them?</strong></p>
  
  <p>Hung ratio is about ~1 per 10000 requests (to 10000 different hosts) and it can last probably forever (I've confirmed thread hung as still valid after 10 hours).</p>
  
  <p>JDK 1.8 on Windows 7.</p>
  
  <p>My <code>HttpClient</code> factory:</p>
  
  <pre><code>SocketConfig socketConfig = SocketConfig.custom()
              .setSoKeepAlive(false)
              .setSoLinger(1)
              .setSoReuseAddress(true)
              .setSoTimeout(5000)
              .setTcpNoDelay(true).build();
  
      HttpClientBuilder builder = HttpClientBuilder.create();
      builder.disableAutomaticRetries();
      builder.disableContentCompression();
      builder.disableCookieManagement();
      builder.disableRedirectHandling();
      builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
      builder.setDefaultSocketConfig(socketConfig);
  
      return HttpClientBuilder.create().build();
  </code></pre>
  
  <p>My <code>RequestConfig</code> factory:</p>
  
  <pre><code>    HttpGet request = new HttpGet(url);
  
      RequestConfig config = RequestConfig.custom()
              .setCircularRedirectsAllowed(false)
              .setConnectionRequestTimeout(8000)
              .setConnectTimeout(4000)
              .setMaxRedirects(1)
              .setRedirectsEnabled(true)
              .setSocketTimeout(5000)
              .setStaleConnectionCheckEnabled(true).build();
      request.setConfig(config);
  
      return new HttpGet(url);
  </code></pre>
  
  <p><a href="http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/native/java/net/SocketInputStream.c" rel="noreferrer">OpenJDK <code>socketRead0</code> source</a></p>
  
  <p>Note: Actually I have some "trick" - I can schedule <code>.getConnectionManager().shutdown()</code> in other <code>Thread</code> with cancellation of <code>Future</code> if request finished properly, but it is depracated and also it kills whole <code>HttpClient</code>, not only that single request.</p>