1

Context

Wanting to learn how to use custom JDialogs for non-trivial, validated data input, I searched and found an interesting answer to a closely related question.

What I don't understand is why the code in the provided answer works.

My Question

Since the JDialog object has executed setVisible(false) and dispose() in the actionPerformed() method of its anonymous ActionListener, by the time the caller gets back program flow and tries to get the fields, shouldn't the Garbage Collector have destroyed this fields already?

Community
  • 1
  • 1
MaxAxeHax
  • 423
  • 7
  • 14

1 Answers1

2

dispose will only dispose of the native peer resources held by the dialog. If you still have a reference to the JDialog in question, it won't be eligible for garbage collection since you still have a strong reference to it. I assuming you still have a reference to the dialog, because otherwise, how else would you be trying to get the values managed by it...

Also garbage collection doesn't happen straight away...

Based on your linked question...

FObjectDialog fod = new FObjectDialog(this);
//...
String name = fod.getName();

There's still a strong reference to FObjectDialog through fod. So, until either fod goes out of the context (the method returns), is dereferenced (fod = null;) or is reassigned, fod (and the dialog by extension) won't be eligible for garbage collection.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Hi again :). Of course it's all about the reference!! Coming from a C++ background, I still have a hard time getting used to have my memory managed "in a smart way" by the JVM. On another note, I was aware that GC might take a while, but it still seems kind of unsafe. I guess I have no clear idea what "native peer resources" entails. – MaxAxeHax Feb 13 '15 at 01:44
  • @MHaaZ Check update. All Swing components share a common native peer (it's associate with each window), it's the connection between the Swing API and the OS and allows Swing to do things like paint, amongst other things. Allow a window to dispose of these resources allows the system to free up memory and is useful when you might want to reuse the window again (something like the `JFileChooser`) as it's faster to re-create the native peer then it is the whole object (at times) – MadProgrammer Feb 13 '15 at 01:46