EJB application shutdown hook
Asked Answered
N

2

6

How would i add a shutdown hook (just like the JVM Shutdown Hook) to listen (get notification) when an EJB application is deployed/undeployed (to stop the JMX MServerBean)?

I could use a ServletContextListener, unfortunately this an EJB jar.

Necessarian answered 29/9, 2011 at 19:58 Comment(0)
G
8

Use @Singleton bean and implement @PreDestroy:

@Startup
@Singleton
public class HookBean {

    @PreDestroy
    void wholeApplicationShuttingDown {
    }
}

UPDATE: Just noticed ejb-3.0 tag. @Singleton was added in 3.1. But still maybe you will find it useful.

Garamond answered 29/9, 2011 at 19:59 Comment(1)
will see if i can upgrade JBoss 5.1 to support ejb3.1 and try it.Necessarian
G
0

Use a Stateless Bean with a @PreDestroy method

Goldsberry answered 29/9, 2011 at 20:2 Comment(9)
Won't work. Stateless beans are pooled - there might be several instances of such a bean or none - if they weren't used. Also you have no guarantee that the container will not destroy all the instances in the pool e.g. in the middle of night just because they weren't used lately.Garamond
@TomaszNurkiewicz Quote from the link above: "Because a stateless session bean is never passivated, its lifecycle has only two stages: nonexistent and ready for the invocation of business methods."Goldsberry
IMHO this doesn't say that the SLSB can't be destroyed at any point in time, but I also don't have a huge experience with EJB. But I know for sure that having a pool of, say, 5 SLSBs will cause 5 invocations of @PreDestroy on each instance. Since the OP wants to do something at shutdown, he needs a synchronized counter of SLSB instances and do the cleanup when it reaches 0. Rather inconvenient.Garamond
@TomaszNurkiewicz I wasn't aware that they are pooled as well, I thought the whole point of being stateless was that they were singletons, but apparently I was wrong. FWIW, in Spring it would work like this :-)Goldsberry
I can feel your pain ;-). And yes, with Spring simple @PreDestroy method on non-lazy bean does the trick... Actually the @Singleton and @Startup annotations were introduced in EJB 3.1 exactly to solve the issue OP is having (there was no reliable startup callback as well...)Garamond
@TomaszNurkiewicz one possible solution: keep a counter that increments on creation of beans and decrements on destruction. If it hits 0, you know it's the last bean, so you can trigger your shutdown work. Dirty hack, but it should workGoldsberry
@Sean Patrick Floyd: let me quote myself: he needs a synchronized counter of SLSB instances and do the cleanup when it reaches 0. Rather inconvenient. - look four comments up ;-). Also there is no guarantee that the container will create even on instance before it shut down...Garamond
@TomaszNurkiewicz sorry, I was blind :-)Goldsberry
thank you all for the suggestions, will try upgrading to ejb3.1 and us the Singleton.Necessarian

© 2022 - 2024 — McMap. All rights reserved.