jakarta-eeejbstateful-session-bean

Are stateful beans managed by container or the application in EJB?


Here is a paragraph from an oracle blog that I read recently.

This behavior is very different from that of Stateful session beans. A Stateful session bean instance needs to be explicitly removed by the client with the invocation of a method annotated with @Remove. It will not be automatically destroyed by the container; it is not bound to any context. If you associate a Stateful session bean with the HttpSession, you also have to care about its reliable destruction at the end or timeout of the HttpSession.

According to this, it is the responsibility of the application to remove stateful session when done using it.

But I have read in a couple of books, if @Remove is not called, the container will still remove the bean from scope but at its own discretion.

so I want to know what is correct? whether @stateful should be explicitly removed or leave it to the container to remove if at all it does the removal

EDIT

I quote from Beginning Java EE7 by Antonio Goncalves - an excellent book; page 243 in pdf

Notice the optional @javax.ejb.StatefulTimeout and @javax.ejb.Remove annotations. @Remove decorates the checkout() method. This causes the bean instance to be permanently removed from memory after you invoke the checkout() method. @StatefulTimeout assigns a timeout value, which is the duration the bean is permitted to remain idle (not receiving any client invocations) before being removed by the container. The time unit of this annotation is a java.util.concurrent.TimeUnit, so it can go from DAYS, HOURS ... to NANOSECONDS (the default is MINUTES). Alternatively, you can avoid these annotations and rely on the container automatically removing an instance when the client’s session ends or expires. However, making sure the stateful bean is removed at the appropriate moment might reduce memory consumption. This could be critical in highly concurrent applications.


Solution

  • It is similar to a FileInputStream. Yes, FileInputStream happens to have a finalizer that will automatically close it if you don't, but the expected programming model is that you will explicitly close it when you're done so that you don't leak file descriptors.

    The same is true for stateful session beans. Yes, the EJB container happens to clean up instances after an access timeout if you don't explicitly remove them (and a standard option even exists to prevent the container from doing it too soon), but the expected programming model is that you will explicitly remove them when you're done so that the resources consumed by the stateful bean instance can be returned to the system.