If I remember correctly, in Java one can write
new JFrame();
without saving the JFrame reference in any variable. This program will display a GUI window on screen and leave it open, until the program is closed. (Please correct me if this premise is false).
Theoretically, we could think that since the JFrame is now unreachable from user code, the GC should at some point free the object. And as a result, the associated OS resources (the GUI window, etc.) will be freed as well.
However, if my understanding is correct - that program is a valid and working Java program (albeit a pretty useless one), and it will not crash or behave in strange ways at any point (again correct me if this premise is wrong).
It seems that the GC will not collect the JFrame object even though there aren't any references to it, or at least it will not cause the associated OS resources to be freed.
I would like to understand: How is this possible?
Does the constructor of
JFramesavethisanywhere in order to not be collected? In the source code forJFrame's superclass java.awt.Frame (methodnoteFrame) the frame seems to be saved in a weak references queue. But since these are weak references, that doesn't seem to explain thingsIs it in fact the case that the GC does eventually free the
JFrame- however, the finalizer method ofJFramedoesn't free the associated OS resources, thus the GUI window stays open?Any other explanation?
Please note that this is a follow up question to a more theoretical question I posted on SE.SE. This question is different because it relates specifically to the Java implementation details.