The Java EE 6 Tutorial says:
To improve performance, you might choose a stateless session bean if it has any of these traits:
- The bean’s state has no data for a specific client.
- In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an email that confirms an online order.
- The bean implements a web service.
Singleton session beans are appropriate in the following circumstances:
- State needs to be shared across the application.
- A single enterprise bean needs to be accessed by multiple threads concurrently.
- The application needs an enterprise bean to perform tasks upon application startup and shutdown.
- The bean implements a web service.
But what to use if:
Say for example I have a login service with the following interface:
public interface LoginService { boolean authenticate(String user, String password); }
Should it be annotated with @Singleton or @Stateless? What are the benefits of the one and the other? What if LoginService needs to get injected an EntityManager (which would be used concurrently)?
Addition: I'm thinking about the Java EE counterpart of Spring service beans, which are stateless singletons. If I understand that correctly the Java EE counterpart are @Stateless session beans and @Singleton Beans are used to configure the application at startup or cleanup at shutdown or to hold application wide objects. Is this correct?
Stateless session beans do not maintain state associated with any client. Each stateless session bean can server multiple clients. Stateful session beans maintain the state associated with a client. Each stateful session bean serves exactly one client.
A stateless singleton is pretty much a collection of static methods; it's no different from a static util class, and it doesn't really matter how many instances there are: 0, 1, 2 or infinity. Therefore singletons are usually stateful.
A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean's instance variables may contain a state specific to that client but only for the duration of the invocation.
Unlike a session bean, a message-driven bean has only a bean class. In several respects, a message-driven bean resembles a stateless session bean. A message-driven bean's instances retain no data or conversational state for a specific client.
I would go for Stateless - the server can generate many instances of the bean and process incoming requests in parallel.
Singleton sounds like a potential bottleneck - the default @Lock value is @Lock(WRITE) but may be changed to @Lock(READ) for the bean or individual methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With