Why OkHttp doesn't reuse its connections?
<p>I'm performing an http-benchmark using OkHttp 3.5.0. I'm sending thousands of requests to the same URL.</p>

<p>I expect that the OkHttp-client uses a ConnectionPool and reuses its connections over and over. But if we look into <code>netstat</code> we'll see many connections in the TIME_WAIT state:</p>

<pre><code>TCP    127.0.0.1:80           127.0.0.1:51752        TIME_WAIT
TCP    127.0.0.1:80           127.0.0.1:51753        TIME_WAIT
TCP    127.0.0.1:80           127.0.0.1:51754        TIME_WAIT
TCP    127.0.0.1:80           127.0.0.1:51755        TIME_WAIT
TCP    127.0.0.1:80           127.0.0.1:51756        TIME_WAIT
...
</code></pre>

<p>After a couple of thousands of requests I'm getting a <code>SocketException: No buffer space available (maximum connections reached?)</code></p>

<p>The code preforming requests (Kotlin):</p>

<pre><code>val client = OkHttpClient.Builder()
        .connectionPool(ConnectionPool(5, 1, TimeUnit.MINUTES))
        .build()

val request = Request.Builder().url("http://192.168.0.50").build()

while (true) {
    val response = client.newCall(request).execute()
    response.close()
}
</code></pre>

<p>If instead of <code>response.close()</code> I use <code>response.body().string()</code>, then <code>SocketException</code> doesn't happen, but <code>netstat</code> still shows plenty of TIME_WAIT connections, and the benchmark performance is getting lower and lower.</p>

<p><strong>What am I doing wrong?</strong></p>

<p>PS: I've tried to use Apache HttpClient and its <code>PoolingHttpClientConnectionManager</code>, and seems like it works perfectly. But I'd like to figure out what's wrong with OkHttp.</p>