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?
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.