I have a service class that has a number of methods that make REST calls to a Spring REST service.
Each of the methods looks like this:
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;
}
The above works fine but i am slightly worried that every time the method is called, new instances of ClientConfig, Client and WebResource are created. What would the side effects be of me changing the above and making ClientConfig, Client and WebResource as class level instance variables? i.e. 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;
}
Is the above likely to fail if multiple users call different methods at the same time? What is the best way to structure the above?
If the Jersey client methods had close() methods, i could have left them the way they were and just close the resources inside the methods.
From Jersey documentation:
For Client:
For WebResource:
While there is no explicit concurrency documentation for
ClientConfig, it’s clear from its source code that its safe to use in a multithreaded environment. TheClientclass is also thread safe, leaving just theWebResourceto consider. Based on its documentation I would dedicate a newWebResourceto each thread, meaning your code should look more like this: