I guess you can intercept the org.jboss.system.server.stopped notification:
You can combine that with a BarrierController. See the example here, it's more or less tailored to what you want:
Just write an mbean service of yours, that in its "stopService" method invokes the shutdown logic on your Session Bean".
Thank you for the great suggestion. I tried it and worked, the only change needed was to set BarrierEnabledOnStartup to true.
Now when I shutdown JBoss with shutdown script my code is working perfectly as the notification send just the moment the server begins shutdown action.
The problem now is when the shutdown is activated through Ctrl + C the same problem occurs. I guess the "org.jboss.system.server.stopped" notification is not broad casted in this case.
I am using JBoss 4.0.3SP1, but still the notification is not send when Shutdown is initiated using Ctrl + C. I saw a related issue in JIRA-2300(http://jira.jboss.com/jira/browse/JBAS-2300).
How can I ensure safe clean up during JBoss shutdown using Ctrl+C also?
If I remember the issue you mention was not a complete fix and I had to fix it properly in 4.0.4.
Maybe upgrade? or again, hook to jvm shutdown.
In my case version upgrade is not possible as customer has fixed it to JBoss 4.0.3 SP1.
If I add the run time hook to JVM I will reach the back to square state since there can be chance that hook start working after the Session Bean has already unbound.
Is there a possibility so that I can ensure that the JVM hook always work before the actual shutdown sequence starts? Or is there some start up parameter setting by which I can ask JBoss to emit the notification during Ctrl + C also?
No, to both questions, you need to patch jboss.
One other option is to make your service depend on the container that hosts the EJB. Before that container is stopped, you should be triggered to stop to, and do the shutdown logic there.
I made my business session bean depend on the MBean service which calls the session bean. So as you suggested before my session beans are undeployed stopService is executed.
As long as this call returns the JBoss shutdown sequence will be suspended.
Thanks for the help!