1

From this thread, I get that even if the programmer has no remaining reference to an object (which becomes unreachable), it may not be ready for garbage collection. An unreachable but running Thread that hasn't been joined yet is such an example. My question is: is an unreachable JFrame that hasn't been closed yet (thus, still having a working and visible GUI interface) ready for garbage collection? If the answer is positive, will this behavior disrupt or force the closing of the GUI interface? For example, the following code snippet is taken from the book Java: A Beginner's Guide:

class SwingDemo {
  SwingDemo() {
    JFrame jfrm = new JFrame("A Simple Swing Application");
    jfrm.setSize(275, 100);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel jlab = new JLabel(" Swing defines the modern Java GUI.");
    jfrm.add(jlab);
    jfrm.setVisible(true);
  }
  ...
}

Note that the JFrame object created is no longer reachable when the SwingDemo constructor returns.

Community
  • 1
  • 1
Lingxi
  • 14,579
  • 2
  • 37
  • 93
  • 1
    Apart from no one having a strong reference to it all any of it's internal components, calling `dispose` or setting the `defaultCloseOperation` to `DISPOSE_ON_EXIT` which will release it's native resources probably wont' hurt. – MadProgrammer Aug 13 '15 at 02:59
  • 1
    See [this](http://stackoverflow.com/questions/9838677/garbage-collector-for-jframes-object) and [this](http://stackoverflow.com/questions/9247746/garbage-collector-for-gui-elements). – Sotirios Delimanolis Aug 13 '15 at 03:00
  • 1
    *"My question is: is an unreachable JFrame that hasn't been closed yet (thus, still having a working and visible GUI interface) ready for garbage collection?"* - No. The Swing toolkit will maintain it's own reference to the frame until it's closed or disposed – MadProgrammer Aug 13 '15 at 03:00
  • More [here](http://stackoverflow.com/q/6309407/230513). – trashgod Aug 13 '15 at 03:16
  • @SotiriosDelimanolis So, the answer lies in the constructor of `JFrame`. – Lingxi Aug 13 '15 at 03:37

1 Answers1

2

One of your assumptions is wrong: the JFrame is reachable, one way is via Windows#getWindows(). The JVM on this method:

Returns an array of all Windows, both owned and ownerless, created by this application. If called from an applet, the array includes only the Windows accessible by that applet.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373