Is it safe to dispose a JDialog in a try block, and then continue executing code in a matching finally block?

StackOverflow https://stackoverflow.com/questions/22690094

Pregunta

I have tried searching around for this question, as I imagine it must have been asked at some point, but this was the closest thing I could find Remove Top-Level Container on Runtime.

My question is, is it safe execute code in a JDialog, after having called dispose() on that dialog, if the dispose is done in a try and the executing code is done in a finally?

Here is an example to demonstrate what I am asking:

import java.awt.EventQueue;
import javax.swing.JDialog;

public class DisposeTestDialog extends JDialog {
    private final String somethingToPrint;

    public DisposeTestDialog(String somethingToPrint) {
        this.somethingToPrint = somethingToPrint;
    }

    public void showAndDispose() {
        setVisible(true);
        // Do something
        setVisible(false);
        try {
            dispose();
        }
        finally {
            System.out.println(somethingToPrint);
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                DisposeTestDialog dialog = new DisposeTestDialog("Can this be safely printed?");
                dialog.showAndDispose();
            }

        });
    }
}

From what I know of the dispose() process, and finally blocks, I would say it should work fine, if not a great idea. Indeed running the above code does successfully print.

Is it possible though that a GC could start in between the try/finally and cause some issue?

¿Fue útil?

Solución

No, as far as you access only non-graphical objects such as string from your example.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top