Miguel Portugal Miguel Portugal - 6 months ago 30
Java Question

Jersey 2.22: When should I close the Client instance?

In my MVC web application, my services rely on the

Client
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
Client
instance:

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
Client
is when the application terminates.

Answer

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.

Comments