不需要清除EJB无状态Bean返回对象的引用。

huangapple go评论67阅读模式
英文:

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

问题

你好,我有点困惑于无状态会话Bean的池机制和内部对象生命周期。根据规范,我理解容器会创建无状态会话Bean并将它们放入池中。池中可能包含多个无状态会话Bean实例,以便重复使用。

我已经阅读了一些书籍。书中没有提到在从EJB无状态Bean返回新创建的对象之后的清理过程。

我需要在无状态会话Bean的方法中创建新实例,填充该实例,并将该实例返回给调用者。例如:

@Stateless
public class MyStatelessBean implements MyLocal {
   public MyDTO myMethod() {
      MyDTO myDTO = new MyDTO();
      // 填充数据...
      return myDTO;   
   }
}

假设调用 MyStatelessBean.myMethod 10 次,那么我们将有 10 个 myDTO 实例。如果再次调用 myMethod 10 次,那么该方法将创建 10 个新的 myDTO 实例,总共将有 20 个,因为无状态Bean的实例会保留在池中。垃圾回收可能不会清除 myDTO 实例的引用,因为Bean仍然在池中存活。如果连续调用 myMethod,那么在某一点上可能会收到内存不足错误。我的假设是否正确?或者在调用类中不需要清除返回对象的引用?

英文:

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?

答案1

得分: 1

你的"myDTO"实例将在从无状态bean的调用者中没有引用它们的情况下被垃圾回收。通常情况下,无状态bean不会保留对其方法内部创建的对象的引用。这取决于调用此方法的方式。

你的代码看起来很好,不应该出现内存不足错误的问题。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月10日 10:34:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定