Search code examples
javaosgiblueprint-osgi

How can I destroy all OSGi blueprint components before the OSGi framework is stopped?


If I stop the OSGi framework, the OSGi blueprint components are not destroyed (destroy methods are not called). Why is this the case and how can I destroy them. I have my own OSGi launcher implementation. I'm using a shutdown hook and then stop the OSGi framework:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        Launcher.logService.log(LogService.LOG_WARNING, "HANDLE SHUTDOWN");
        if(Launcher.framework != null) {
            try {
                Launcher.framework.stop();
            } catch (BundleException e) {
                Launcher.logService.log(LogService.LOG_ERROR, "Shutdown" + ((Launcher.framework != null) ? " of " + Launcher.framework.getSymbolicName() + " " : " ") + "failed!", e);
                System.exit(-1);
            }
        }
    }
});

Solution

  • We should wait for the framework to stop.

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            Launcher.logService.log(LogService.LOG_WARNING, "HANDLE SHUTDOWN");
            if(Launcher.framework != null) {
                try {
                    Launcher.framework.stop();
                    Launcher.framework.waitForStop(0); // !!!
                } catch (BundleException e) {
                    Launcher.logService.log(LogService.LOG_ERROR, "Shutdown" + ((Launcher.framework != null) ? " of " + Launcher.framework.getSymbolicName() + " " : " ") + "failed!", e);
                    System.exit(-1);
                }
            }
        }
    });