Life Cycle of JAX-RS Resource Class

When a request comes for a REST Service, how the JAX-RS runtime initiate it? Does it keep only one object of the JAX-RS resource and spawn a new thread for each request? Or does it initiate a new object of that JAX-RS Resource class for each request? Let’s answer these questions.

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.

So when accessing the resource though the URI web-app/resource/someURI, We know the following steps are happening:

  1. All classes with a @Path annotation are searched for the matching path, so the example Resource will be found because web-app/resource/someURI has the closes match to the web-app/resource/{identifier}
  2. Next the constructors of the class are scanned for the closest match. If no additional config has been made, then default constructor would be called.
  3. when the resource is constructed, and the injection can begin. It scans the instance field for known annotations and initializes those fields.
  4. And finally the methods are scanned for annotations (another path annotation or the http verbs).
  5. After the request is complete, the resource is de-referenced and is prepared to be garbage collected.

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.

Though, you can make Resource classes singleton explicitly if you want to. For example, by default Jersey creates a new instance of the resource class for every request. So if you don’t annotate the Jersey resource class, it implicitly uses @RequestScoped scope. If you want to create a singleton Jersey resource class by using @Singleton annotation, then you need to register the singleton class in the Application class, e.g.,

@Path("/resource")
@Singleton
public class JerseySingletonClass {
    //methods ...
}
 
public class MyApplication extends ResourceConfig {
 
    /*Register JAX-RS application components.*/
    public MyApplication () {
        register(JerseySingletonClass.class);
    }
}

Happy Learning !!

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.