I am developing a RESTful Web Service and while reading the Jersey documentation I came across an annotation @Singleton
In my web service I am mostly returning data based on the unique keys provided as parameter. An analogy would be return all the information of a Student when the Student_Id is passed.
So my question is when @Singleton
would be suited in such kind of Web Services?
As per documentation for @RequestScoped
If the resource is used more than one time in the request processing, always the same instance will be used.
Then in that case we should not bother to use @Singleton
right?
Also what could be the use cases where we have to make a new instance for every request?
I did have a look at this post but my question was not answered.
There is actually a use case specified in the Jersey 2 manual for using the SseBroadcaster when serving Server-Sent events, it is covered in this provided example
Using the
@Singleton
, The application will only contain oneSseBroadcaster
for all incoming requests, one such broadcaster is enough to serve multiple clients, so it only needs to be instantiated once!In most cases default scope
@RequestScoped
should be sufficient for your needs.@Singleton
may hold state. I had the problem when my endpoint was annotated as@Singleton
so it reused the sameEntityManager
during concurrent calls. After removing@Singleton
, during concurrent calls, differentEntityManager
object instances are used. If endpoint calls are subsequent, it may be that previous/oldEntityManager
will be used. - Jersey, Guice and Hibernate - EntityManager thread safetyBy 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. It is stated in Jersey documentation:Most cases you use this default setting so you don't use
@Singleton
scope. You can also create a singleton Jersey resource class by using@Singleton
annotation. Then you need to register the singleton class in theMyApplication
class, e.g.,