Jersey Customer Services - Closing Resources

I have a service class that has a number of methods that make REST calls to a Spring REST service. Each of the methods is as follows:

public void getUser() { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(RESOURCE_URL); // Get response as String String response = service.path("/addUser").accept(MediaType.TEXT_PLAIN) .get(String.class); return response; } 

This works fine, but I'm a little worried that every time the method is called, new instances of ClientConfig, Client, and WebResource are created. What would be the side effects associated with changing the above and creating ClientConfig, Client, and WebResource as class instance variables? those. change to this:

 ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(RESOURCE_URL); public void getUser() { // Get response as String String response = service.path("/addUser").accept(MediaType.TEXT_PLAIN) .get(String.class); return response; } public void getUserAccount() { // Get response as String String response = service.path("/getUserAccount").accept(MediaType.TEXT_PLAIN) .get(String.class); return response; } 

Perhaps this is higher if several users call different methods at the same time? What is the best way to structure the above?

If the client methods in Jersey had close () methods, I could leave them as they are and just close the resources inside the methods.

+4
source share
1 answer

From Jersey Documentation :

For Client :

Ways to create WebResource instances are thread safe. methods that changing the configuration and / or filters are not guaranteed to be thread safe.

Creating a client instance is an expensive operation, and an instance can use and save a lot of resources. Therefore, it is recommended that the client instance be reused to create WebResource Instances that require the same configuration settings.

For WebResource :

Ways to create a request and return a response are thread safe. Methods that modify filters are not guaranteed to be thread safe.

While there is no explicit concurrency documentation for ClientConfig , it is being cleared of the source code, which is safe to use in a multi-threaded environment. The Client class is also thread safe, leaving only WebResource to consider. Based on his documentation, I would allocate a new WebResource for each thread, which means your code should look something like this:

 ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); public void getUser() { WebResource service = client.resource(RESOURCE_URL); // Get response as String String response = service .path("/addUser") .accept(MediaType.TEXT_PLAIN) .get(String.class); return response; } 
+10
source