views:

904

answers:

2

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();
+1  A: 

I think what you have is as good as its going to get using Java's implementation. If speed is a huge concern and Java's implementation is hogging memory or is too slow, write your own connection class.

twolfe18
agree, haven't seen any performance issues
Pete
+3  A: 

You might consider using Apache's HttpClient. We use it in an app that sends requests, literally, a couple million times a day load balanced over a handful of systems. We've use a pool of the HttpClient objects, which I'm not sure is necessary since we don't keep the connections open between calls, but the code predates my time here and maybe they found a reason for it.

Chris Kessel
Thanks, didn't seem to need to go this far, current code appears to be fine.
Pete