javajakarta-eeejb-3.1

Accessing stateless EJBs in PreDestroy method of Singleton


I have a problem accessing stateless EJBs in the preDestroy method of an singleton. I need to log the shutdown of the application server in an database table.

This is what the singleton looks like:

  @Startup
  @Singleton
  public class ServerShutdown {

     @EJB
     TableFacade tableFacade;

     @PreDestroy
     private void shutdown() {
        TestEntity e = tableFacade.find("test");
        //do something

     }
  }

Here's example code of the stateless bean:

@Stateless
public class TableFacade {

...

   public TestEntity find(String test) {
      Query query =       
      getEntityManager().createNamedQuery("TestEntity.namedQuery");
      return (TestEntity) query.getSingleResult();
   }
}

If the server is shutting down, the preDestroy method is accessed and the EJB method is called. But during the call, the server seems to force the shutdown process and cancels the calling of the EJB method.

I'm using Java EE 6, JDK 1.8, EJB 3.1, eclipselink 2.5.2.

Thanks in advance


Solution

  • The @predestroy should only do ejb resource cleanup, such as connection, variable etc...

    Your problem has to do with the transaction context, infact from the spec:

    The PreDestroy lifecycle callback interceptor methods for stateless and stateful session beans execute in an unspecified transaction context.

    And then:

    For example, it would be wrong to perform database operations within a stateful session bean’s PostConstruct or PreDestroy lifecycle callback interceptor methods and to assume that the operations are part of the client’s transaction. The PostConstruct and PreDestroy methods for stateful and stateless session beans are not controlled by a transaction attribute because handling rollbacks in these methods would greatly complicate the session instance’s state diagram.

    So, it is not explicitly forbidden, but you are warned that things may go wrong.