简体   繁体   中英

OkHttp connection leaks due to cloned client

I'm working on an issue related to Okhttp connection leaks. The leak stack trace seems to pointing to this WebSocket connection being opened in PodOperationsImpl #L267:

        try {
            URL url = new URL(URLUtils.join(getResourceUrl().toString(), sb.toString()));
            Request.Builder r = new Request.Builder().url(url).header("Sec-WebSocket-Protocol", "v4.channel.k8s.io").get();
            OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build();
            final ExecWebSocketListener execWebSocketListener = new ExecWebSocketListener(getConfig(), in, out, err, errChannel, inPipe, outPipe, errPipe, errChannelPipe, execListener);
            clone.newWebSocket(r.build(), execWebSocketListener);
            execWebSocketListener.waitUntilReady();
            return execWebSocketListener;
        } catch (Throwable t) {
            throw KubernetesClientException.launderThrowable(forOperationType("exec"), t);
        }

When I run the test provided in the issue itself, I see connection leak messages on logs:

WARNING: A connection to http://localhost:48271/ was leaked. Did you forget to close a response body?
java.lang.Throwable: response.body().close()

But when I create OkHttpClient from a new instance instead of cloning it from the previous one, these connection leak warnings are reduced by 3/4th. Is cloning client prone to connection leaks? Or whether I'm not doing it the right way? Is there any way to ensure if we can handle these connection leak warning messages?

One more thing, the websocket is opened using ExecWebSocketListener , which already implements AutoCloseable . Although doing try-with-resources from caller does seem to avoid these warnings. But I'm not sure whether it's actually fixing the root cause of leaks.

The clone is unrelated. This warning relies on the garbage collector to find instances that went out of scope before they were closed, and this process is neither immediate nor particularly reliable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM