Search code examples
javaejbjava-ee-6

Does the EJB container removes all the EJB objects in call hierarchy if last EJBBean method throws SystemException?


Following is some sudo code:

//controller method
public String method1()
{
    EJBBean1 bean1;
    bean1.method1();
}

//EJBBean1 class
public void method1()
{
    EJBBean2 bean2;
    bean2.method2();
}

//EJBBean2 class
public void method2()
{
    EJBBean3 bean3;
    bean3.method3();
}

//EJBBean3 class
public void method3()
{
    throw NullPointerException();
}

The EJB objects are injected through dependency injection.

Does the EJB container removes all the EJB objects (EJBBean1, 2 & 3) if method3 of EJBBean3 throws SystemException?


Solution

  • In Normal Case

    Nested StateFullEJB has special behavior , The contained EJB Holds the session.

    In your case, EjbBean1 holds new dedicated EjbBean2 when EjbBean1 get destroyed EjbBean2 also would get destroy. Same case applies to EjbBean2 - EjbBean3 .

    So it is EjbBean1 responsibility to call the remove in EjbBean2.remove in EjbBean1.remove method ( @Remove method).

    Samples

    And for the Exception case....

        When ever a System Exception thrown by a bean method, EJB Container invalidates 
    the EJB object and destroys the bean instance.The bean instance directly moved into
     DOES not exists state and any @PreDestroy methods are not invoked.
    
    A System  exception is any unchecked Exception not annotated as an @Application Exception 
    

    Refer here

    Thus your EjbBean3 will be destroyed automatically by the Ejb Container and the exception propagates to Parent method EjbBean2 and EJbBean1 . Since none of the bean is catching the NullPointerException these instances would remove automatically by the container.

    NOte** , Assumed NullPointerException is an System Exception ( i.e not annotated / configured )