I am using Jersey v10 and have written the following code.Is this the right way to close a Jersey client connection to avoid memory leaks.I was not doing any calls int he finally before this.
ClientConfig config = setupHttps();
final Client c = Client.create(config);
final WebResource r = c.resource(baseUri);
ClientResponse response = null;
try {
response = r.path("/....")
.header("contentId", id)
.header("sid", sid).get(ClientResponse.class);
...
} catch (Exception e) {
log.error("Error returning contentServiceName.");
} finally {
if (response != null) {
response.close();
}
if (c!= null) {
c.destroy();
}
}
TIA, Vijay
As far as I know, yes, this is the right way to close a Jersey client ... with the following caveats.
1) What you're trying to prevent is not memory leaks, but connection (to the server you're addressing) leaks ...
2) The following is written about the Client class in Chapter 3 of the Jersey Handbook:
Client instances are expensive resources. It is recommended a configured instance is reused for the creation of Web resources. The creation of Web resources, the building of requests and receiving of responses are guaranteed to be thread safe. Thus a Client instance and WebResource instances may be shared between multiple threads
Therefore, if you're planning on making multiple calls, it's a good idea not to call destroy for every call. The same (but to a lesser extent) is true for WebResources.
3) What I'm describing is from Jersey 1.1 (but I see threads about this as far back as 2009).