javajakarta-eememory-leaksejbejb-3.1

Do I need to clear the reference of return object from EJB Stateless Bean?


Hi I am little confused with stateless session bean's pool mechanism and internal object lifecycle. According to the spec, I understood that the container creates stateless session beans and put them in the pool. The pool may contains multiple stateless session bean instances for reusing purpose.

I have read few books. Books do not say anything about clean up procedure after returning newly created object from EJB stateless bean.

I have to create new instance inside the method of stateless session bean, populate the instance and return the instance to the caller. For example:

@Stateless
public class MyStatelessBean implements MyLocal{
   public MyDTO myMethod(){
      MyDTO myDTO = new MyDTO();
      ...
      ...
      return myDTO;   
   }
 }

Suppose, the MyStatelessBean.myMethod is invoked 10 times, then we have 10 myDTO instances. If I call myMethod 10 times again then the method will create 10 more myDTO instances and total will be 20 because instance of stateless bean will stay in the pool. GC may not clean up the references of myDTO instances because beans are still alive in the pool. If myMethod is call continuously, I will probably receive Out Of Memory error at one point. Is my assumption correct? Or I do not need to clear the reference of returned object in the caller class?


Solution

  • Your "myDTO" instances will be garbage collected as soon as there are no reference to them from the caller to this stateless bean. Stateless bean in general does not keep any reference to the objects created locally inside of its method. It's depend on how you use them from the caller of this method. Your code look good and should not have any issue with Out of Memory error.