Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How will a Rest Service execute when a user access a resource from resource class?

When multiple users are requesting the same resource method from a service class, how will requests be handled at the server?

How will a rest service execute for each request? How different the execution life cycle of rest service from the servlet execution?

For example, if below is the Resource, how will it be instantiated and executed in the following scenarios:

case 1: two users call the two different methods at a time

case 2: two users call the same method at a time

@Path("greet")
public class GreetingResource {

    @GET
    @Path("welcome/{username}")
    @Produces(MediaType.TEXT_PLAIN)
    public String sayWelcome(@PathParam("username") String User) {
        return "Welcome!" + User;
    }

    @GET
    @Path("hello/{username}")
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello(@PathParam("username") String User) {
        return "Hello " + User;
    }
}
like image 354
Sagar Pudi Avatar asked Jan 03 '23 16:01

Sagar Pudi


1 Answers

From Jersey documentation which is JAX-RS implementation:

Default lifecycle (applied when no annotation is present). In this scope the resource instance is created for each new request and used for processing of this request. If the resource is used more than one time in the request processing, always the same instance will be used. This can happen when a resource is a sub resource and is returned more times during the matching. In this situation only one instance will serve the requests.

From Life Cycle of JAX-RS Resource Class:

By default the life-cycle of root resource classes is per-request which, namely that a new instance of a root resource class is created every time the request URI path matches the root resource.

In short, following things happen in sequence.

Path’s are matched with Resource classes.
Constructor is called.
Dependencies are injected.
Appropriate method is called.
Resource is garbage collected.

Strangely, JAX-RS resource classes are not by default singleton. In general this is unlikely to be a cause of performance issues. Class construction and garbage collection of JVMs has vastly improved over the years and many objects will be created and discarded to serve and process the HTTP request and return the HTTP response.

While endpoint class is created new upon request by default, you can make it singleton to have one instance per JAX-RS application: JAX-RS Resource Lifecycle Performance Impact

Talking about your examples, in both case 1 and 2 instantiation wouldn't differ and users would use 2 instances of GreetingResource and get their name on return. In case 2, if the method would use database and 2 users would modify the same resource, you would need to manage concurrent access with optimistic locking or other solution.

like image 132
Justinas Jakavonis Avatar answered Jan 05 '23 18:01

Justinas Jakavonis