Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS Resource Lifecycle Performance Impact

I know by default JAX-RS endpoints lifecycle is once-per-request, so that the request specific informations can be injected into the instance.

And we can also make an endpoints Singleton meaning once-per-application, in which the request specific informations cannot be injected into the instance rather it can be injected into the requested method.

1. So i would like to know which approach is better in terms of performance, either once-per-request or once-per-application.

2. I would also like to know the pros and cons of these approaches other the injecting request specific informations

3. Which approach you prefer to use in your API applications

Note: i have been using the once-per-request approach so far, but i always wonder is that is efficient, definitely its make coding easier and reusable.

like image 408
Ramesh Lingappa Avatar asked May 23 '15 06:05

Ramesh Lingappa


1 Answers

To start with your last question: I'm always using the default (per-request) and I seldom came to a point where I wanted to change this.

What might be a reason to prefer one over the other?

  • If you want to serve some static content (maybe a welcome-document of your API) it makes sense to produce this content only once and hold it in a singleton resource class. But you can achieve the same by e.g. injecting an @ApplicationScoped CDI bean in a per-request scoped resource class.
  • If you prefer injecting the @xxxParam values like @QueryParam as fields instead of method parameters you should use the per-request lifecycle. This is not supported for singletons. (This does not include injecting via @Context).

I made a little test to compare the performance of both. You can find the sources and the results on github. In short: I measured a difference from about 1.5 %. I don't think this should affect your application too much. Comparing the results of the JVisualVM monitoring I would tend to say that the per-request test is using more memory but you should decide on your own if this really affects your application.

like image 135
lefloh Avatar answered Sep 28 '22 03:09

lefloh