0

When to use @Singleton annotation of Jersey? -

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.

@RequestScoped endpoint looks more suitable for various reasons. It is stateless, provides new instance for each request. I have implemented DAO's based on http://www.benmccann.com/hibernate-with-jpa-annotations-and-guice example so provided EntityManager objects are different only in @RequestScoped environment because they are received from ThreadLocal<EntityManager> cache (Jersey, Guice and Hibernate - EntityManager thread safety).

On the other hand, I have faced applications where Jersey endpoints are annotated as @Singleton. But it seems that removing annotation won't change application behavior/logic.

When @Singleton should be used instead of default @RequestScoped for REST endpoint?

Community
  • 1
  • 1
Justinas Jakavonis
  • 8,220
  • 10
  • 69
  • 114

1 Answers1

1

It doesn't matter in REST-application much - unless you have a session based rest api (Hint: Don't do that, that's not the point of REST).

Singleton can get slow (in Jersey) as jersey uses a single class loader and when your API is busy replying to someone else, then all other requests to that endpoint could take a while until the former is finished.

Mio Bambino
  • 544
  • 3
  • 15