gravatar

EJB's and Exceptions

EJB's and Exceptions
From an EJB method, if any unchecked excpetion is thrown, then it will be encapsulated in EJBException object...All checked exceptions are propagated without getting encapsulated by any other exception..

This is true for both Stateful and Stateless EJB's

Session Beans  and Exceptions
Whenever an EJB method throws any uncheked exception, then the container invalidates the EJB instance...During this process the container does'nt call the lifecycle listener method marked with PreDestroy...
When a checked exception is thrown, then the EJB instance is not invalidated...

When we say invalidated, it can mean many things..Its exactly implementation depends on the Application Server...However, the main thing to know is that, all further EJB method calls will be dealt by a different EJB instance...Some servers, might destroy the EJB completely...while some servers, return the instance to the EJB instance pool...

For Stateful Bean also when an Unchecked exception is thrown, the EJB Bean is completely destroyed...So we cannot call any other methods of the stateful EJB bean once an Uncheked exception is thrown (In case of stateful EJB, we can continue calling EJB methods, as a new EJB instance will be assigned for each method invocation)...For Checked exception, there is no problem...just like in stateless EJB..

@PreDestroy lifecycle callback method

The @PreDestroy method may not be called in all situations...When a Bean (stateful or stateless) is invalidated  then the method marked with the annotation "PreDestroy" does'nt get called...When the session bean timesout, the server may not call this lifecycle method (You have to contact the server doc for this)..

When a stateful bean has a method that is marked with the @Remove annotation and when the client calls this method, then the method marked with the annotation @PreDestroy will be called...

NOTE: When a method is marked with @Remove and @PreDestroy, then the method will be called twice when a client invokes the method once...