7 Replies Latest reply on May 16, 2016 6:58 AM by chrisjr

    In which order does Weld destroy @ApplicationScoped beans?

    chrisjr

      Hi,

       

      I have a WELD 2.3.4/Tomcat 8 application that runs in AWS; AWS "auto-scaling" means that my instances of my application will be started and stopped quite aggressively. I have therefore been examining how my application shuts itself down to ensure that nothing is lost. However, I have noticed that WELD is executing the @PreDestroy methods for some @ApplicationScoped beans while there are still other beans that are actively depending on them! I had always assumed that WELD calculated some kind of "dependency graph" internally so that it could destroy beans in some "safe" order, but this doesn't appear to be the case.

      My particular application involves several @ApplicationScoped beans that are instantiated immediately by observing an @Initialized(ApplicationScoped.class) event. And then these beans are injected as dependencies into a set of @Dependent "worker" beans. (Yes, these workers are managed beans). However, when the application shuts down, I am seeing the @ApplicationScoped beans destroyed first. The worker beans' @PreDestroy methods then fail because services that they require are no longer available. I can probably construct an example application, if this is a WELD bug - although I am suspecting that it isn't really, and that WELD makes no guarantee about the order in which it invokes @PreDestroy methods. Is this correct, please?

      I have noticed that I can observe a @Destroyed(ApplicationScoped.class) event, which is dispatched before any @PreDestroy methods are called. However, this observer method cannot replace a @PreDestroy method for a @Dependent scoped bean! And CDI 1.2 doesn't allow me to control the order in which @Destroyed(ApplicationScoped.class) events are received any more than it appears to for invoking @PreDestroy methods anyway.

      I have currently migrated some "clean-up" work out of @PreDestroy methods and into other @ApplicationScoped beans' @Destroyed event handlers, but it does seem that I've mangled the application slightly doing this. Have I missed anything about how WELD shuts applications down, please?

       

      Thanks,

      Chris