Stefan S.
Stefan S.

Reputation: 4103

Run Code On Application Close

This is a very common problem yet again, and yet again it seems there is no real support in E4 (but if I remember correctly, it did not work in E3 either).

I want to close my database connection when the application closes. Or more general: I want to do any kind of clean up on exit.

So the usual API for this is:

public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

    public ApplicationWorkbenchWindowAdvisor(final IWorkbenchWindowConfigurer configurer) {
        super(configurer);
    }

    @Override
    public boolean preWindowShellClose() {
        if (PlatformUI.getWorkbench().getWorkbenchWindowCount() <= 1) {
            // the last window is about to close
            Datababase.close();
        }
        return super.preWindowShellClose();
    }
}

The problem? It's not called every time the application closes, especially not on PlatformUI.getWorkbench().close(); (even though the JavaDoc claims this method closes the windows).

(If you want to test if this claim is correct, just use the ExitHandler to close your application - preWindowShellClose() is not called then.)

I could create my own handler and manually call the clean up methods yet again, but I was hoping there was a better way.

Another way you could react to a application shutdown is the Shutdown Hooks API:

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    Datababase.close();
}));

Problem: for an RCP application, this hook is called way, way, way too late, e.g. all plug-ins are already closed then.

I feel there must be a simple (and working) way, I just haven't found it yet. If it's important, we are using the Lesser Evil Eclipse (aka E3 compatibility).

How do I run code whenever an application closes?

Upvotes: 1

Views: 131

Answers (1)

R&#252;diger Herrmann
R&#252;diger Herrmann

Reputation: 20985

Use IWorkbench::addWindowListener or IWorkbench::addWorkbenchListener to get notified when a workbench window is closed or the workbench is shut down.

You may also consider running the clean up code from you bundle's stop method.

Upvotes: 2

Related Questions