Miguel Portugal Miguel Portugal - 8 months ago 35
Java Question

Jersey 2.22: When should I close the Client instance?

In my MVC web application, my services rely on the

instance to create HTTP requests to a web service. According to the Jersey documentation, it is quite expensive to initialize and destroy client objects so what I did was I just created a singleton

private static final Client client = ClientBuilder.newClient();

My question is, when should I close this instance? Because it seems like the only time I wouldn't be using the
is when the application terminates.


If you define it as a Singleton in some fashion then you don't really need to - it lives and dies with your application. Sometimes, you might define a Client instance for a specific short- or medium-term need (say you have an application which speaks to multiple remote endpoints which change during the lifetime of the application). In those cases it would be best to explicitly close the Client 'at some point' to make it clear that it's not intended for reuse. The tricky part might be defining what 'at some point' really means.