Search code examples
javamultithreadingjerseyjax-rs

How to use JerseyClient in a JAX-RS resource in thread-safe manner


in the following UserResource class:

public class UserResource {
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/users")
    public void createUser() {
        //JerseyClient is needed to send a REST request to another RESTful service
    }
}

JerseyClient is needed to send request to another RESTful API as mentioned in the comment.

As in the same time there might be multiple threads calling this UserResource, the JerseyClient probably should be initialized in each call per thread to be thread-safe. However, the JAX-RS Client mentioned

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. Client instances must be properly closed before being disposed to avoid leaking resources.

Based on the documentation, it is probably expensive to initialize the JerseyClient inside the createUser body, and thus bring about the performance issue.

Question: How to optimize the amount of JerseyClient instances efficiently in thread-safe manner?


Solution

  • It's enough if you instantiate your Client as a class field, as the Client class is thread-safe.

    The Jersey documentation says:

    Client instances are expensive resources. It is recommended a configured instance is reused for thecreation of Web resources. The creation of Web resources, the building of requests and receiving ofresponses are guaranteed to be thread safe. Thus a Client instance and WebResource instances maybe shared between multiple threads.