How can I get my basic SWT application to exit properly in Mac OS X 10.5.6?

Alex Reynolds picture Alex Reynolds · Jan 27, 2009 · Viewed 10.5k times · Source

I have the following SWT test code:

public static void main(String[] args) {
    shell = new Shell();
    shell.setText(APP_NAME + " " + APP_VERSION);
    shell.addShellListener(new ShellListener() {
        public void shellActivated(ShellEvent event) { }
        public void shellClosed(ShellEvent event) { exit(); }
        public void shellDeactivated(ShellEvent event) { }
        public void shellDeiconified(ShellEvent event) { }
        public void shellIconified(ShellEvent event) { }
    });     
    shell.open();
    display = shell.getDisplay();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

My exit() method is as follows:

private void exit() {
    System.exit(0);
}

I try to quit the application by closing the shell ("window") or by pulling down the application menu (labeled "SWT") and selecting "Quit".

When I do this, a SWT stub is left behind in the Dock and the SWT application has not actually exited. I have to manually terminate the SWT application through Eclipse or via Force Quit.

I have tried this with the v3.4 and v3.5 SWT jars, under Eclipse 3.4.1 under Mac OS X 10.5.6 (Intel).

Is there additional work I need to do to be able to quit the application when I close the shell?

Answer

McDowell picture McDowell · Jan 27, 2009

You are not releasing the native resources correctly - you have a resource leak.

You don't need to do this:

private void exit() {
    System.exit(0);
}

The main method will exit when the shell is disposed. If you must use an exit method, call it after you've disposed all SWT resources:

    Display display = new Display();
    try {
        Shell shell = new Shell(display);
        try {
            shell.open();
            while (!shell.isDisposed()) {
                if (!display.readAndDispatch()) {
                    display.sleep();
                }
            }
        } finally {
            if (!shell.isDisposed()) {
                shell.dispose();
            }
        }
    } finally {
        display.dispose();
    }
    System.exit(0);