I have a use case where a servlet (that has reasonably high concurrent use) makes an outgoing URLConnection to retrieve some data REST style as part of its normal server-side processing logic. The connection is created and used each time the servlet is invoked as the URL is potentially different (but the domain is always the same). I want to ensure that it does this as optimally as possible, so that ports and connections are not held open longer than they need to be on the application server, but are re-used if applicable.
The Javadocs seem a bit vague - on URLConnection:
'Invoking the close() methods on the InputStream or OutputStream of an URLConnection after a request may free network resources associated with this instance, unless particular protocol specifications specify different behaviours for it.'
On HttpURLConnection:
'Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.'
Currently, a URLConnection is being used and the inputstream closed only, as per the code below (error handling and URL reading removed as they are not relevant to the question). My thought is this will clean up stream resources but allow re-use of the underlying socket if possible (since the request is always to the same domain, with different URL paths). Any advice on how to further optimize would be appreciated.
URL requestUrl = new URL(location);
URLConnection urlConnection = requestUrl.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
//reading code here
br.close();