In our existing codebase, due to the JAX-RX Client API document:
Clients are heavy-weight objects that manage the client-side communication infrastructure. Initialization as well as disposal of a Client instance may be a rather expensive operation. It is therefore advised to construct only a small number of Client instances in the application.
The javax.ws.rs.client.Client
was used as a singleton inside the Resource. The code looks like:
@Path("test")
public class TestResource {
private Client client = ClientUtil.getInstance();//Get the singleton Client instance
@PUT
@Produces("application/json")
public String update(@Context UriInfo uri,
@Context HttpHeaders headers) {
...client is used for sending request to some other service
}
}
Problem: The TestSource
is not used by a single user but multiple users and, each of them uses its own credential, meaning each user has its own configuration. The following method chain is bound to be called in any case:
client.getTarget()
.request()
.header(HttpHeaders.AUTHORIZATION, "authorization header value")
....
=> concurrency issue
Question 1: Is the javax.ws.rs.client.Client instance in the code thread-safe?**Question 2: If not thread-safe, how to resolve the thread-saftey issue? Should I synchronize this singleton Client instance? or try to make each user have it own Client instance and maintain it in a thread-safe collection? or are there any better alternative solutions?