When all the data in the input stream is consumed, the connection is automatically released and added to the connection pool. The main socket connection is not freed, suggesting that the connection will be reused in the near future. It is good practice to call disconnect in the finally block, as it takes care of releasing the connection in case of exceptions .
Here is the implementation of the FixedLengthInputStream reading method :
@Override public int read(byte[] buffer, int offset, int count) throws IOException { Arrays.checkOffsetAndCount(buffer.length, offset, count); checkNotClosed(); if (bytesRemaining == 0) { return -1; } int read = in.read(buffer, offset, Math.min(count, bytesRemaining)); if (read == -1) { unexpectedEndOfInput();
When the bytesRemaining parameter becomes 0, endOfInput is called , which will use the release method with the true parameter, which will ensure pooling.
protected final void endOfInput(boolean reuseSocket) throws IOException { if (cacheRequest != null) { cacheBody.close(); } httpEngine.release(reuseSocket); }
Here is the implementation of the release method. The latter, if verification ensures that the connection must be closed or added to the connection pool for reuse.
public final void release(boolean reusable) { // If the response body comes from the cache, close it. if (responseBodyIn == cachedResponseBody) { IoUtils.closeQuietly(responseBodyIn); } if (!connectionReleased && connection != null) { connectionReleased = true; // We cannot reuse sockets that have incomplete output. if (requestBodyOut != null && !requestBodyOut.closed) { reusable = false; } // If the headers specify that the connection shouldn't be reused, don't reuse it. if (hasConnectionCloseHeader()) { reusable = false; } if (responseBodyIn instanceof UnknownLengthHttpInputStream) { reusable = false; } if (reusable && responseBodyIn != null) { // We must discard the response body before the connection can be reused. try { Streams.skipAll(responseBodyIn); } catch (IOException e) { reusable = false; } } if (!reusable) { connection.closeSocketAndStreams(); connection = null; } else if (automaticallyReleaseConnectionToPool) { HttpConnectionPool.INSTANCE.recycle(connection); connection = null; } } }
Note. I previously answered a couple of SO questions related to HttpURLConnection that may help you understand the basic implementation. Here are the links: Link1 and Link2 .
source share