Alex Rivera | Logout

Stateless Session Beans vs. Singleton Session Beans

Asked 2010-01-06T15:27:31.777
31

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:

  • no state has to be shared across the application
  • a single enterprise bean could be accessed by multiple threads concurrently
  • no tasks on startup or shotdown need to be performed

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?

Edit
Report

2 Answers

12

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.

answered 2010-01-06T16:05:17.550
0

I think you should use Singleton session bean. Because a login service should be a global service and it does not need to store any state for a concrete user or invocation.

answered 2013-07-05T06:24:44.173

Your Answer