adam bien's blog

@Stateful vs. @SessionScoped 📎

CDI's @SessionScoped annotation specifies CDI beans maintained within a HTTP session:

"...The session context is shared between all servlet requests that occur in the same HTTP session. The session context is destroyed when the HTTPSession times out, after all HttpSessionListener's have been called, and at the very end of any request in which invalidate() was called, after all filters and ServletRequestListener s have been called..."
JSR 346: Contexts and Dependency Injection for JavaTM EE 1.1,[6.7.2 Session context lifecycle]

The EJB @Stateful annotation denotes classes which are entirely controlled by the client. Their lifecycle is completely independent from HTTP session. In fact EJBs could be even present in environments without an installed servlet container.

An @Stateful EJB instance is exclusively created for a client when:

"...A session bean instance’s life starts when a client obtains a reference to a stateful session bean instance through dependency injection or JNDI lookup, or when the client invokes a create METHOD method on the session bean’s home interface..."
The same instance is destroyed in case:
"...When the client calls a business method of the bean that has been designated as a Remove method on the bean class or a remove method on the home or component interface, the container invokes PreDestroy lifecycle callback interceptor methods, if any, for the bean instance after the Remove method completes..."
JSR 345: Enterprise JavaBeansTM 3.2, [4.6 Stateful Session Beans]

Although the names are similar, @Stateful and @SessionScoped behave differently. @SessionScoped bean instances are maintained within the HTTP session. Only one instance of a given class can exist within a HTTP session. All @SessionScoped instances are destroyed together with the HTTP session.

@Stateful EJBs, on the other hand, maintain usually 1:1 relation between an instance and the client. The client is completely in charge of creating and destroying the instances. A single client (=usual Java class) could even maintain multiple @Stateful instances.

@Stateful EJBs can be also denoted with @SessionScoped annotation. Then the active HTTP session becomes the "EJB client" and maintains the instances.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.