0

I have read the thread What are the roots?, but it doesn't address my question. That thread basically explains under what condition is an object ready for garbage collection. The question here is whether the condition is met in certain circumstances, and if so, whether such behavior will lead to problems.

By the term active, I take to mean something like:

  1. a Thread object that hasn't been joined yet, and
  2. a JFrame object that hasn't been closed yet (still having a visible GUI interface).

In the book Java: A Beginner's Guide, I frequently find code that creates some objects and then discards the only (apparent) reference to them while they are still active. Will this results in possible premature garbage collection and causes certain problems, or the runtime system actually has a reference to these active objects (thus the parenthesized apparent in the preceding text), so it is OK for the programmer to have none? Following are two examples:

1) Concerning Thread:

{
  Thread thrd = new Thread(...);
  ...  // no thrd.join();
}

2) Concerning JFrame:

class SwingDemo {
  SwingDemo() {
    JFrame jfrm = new JFrame("A Simple Swing Application");
    ...
    jfrm.setVisible(true);
  }
  ...
}
Community
  • 1
  • 1
Lingxi
  • 14,579
  • 2
  • 37
  • 93
  • @SotiriosDelimanolis I have edited the question to explain why it is not a duplicate. Please confirm. – Lingxi Aug 13 '15 at 02:14
  • You're going at it "backwards". Since a thread is a GC root, it (and anything reachable through it) cannot be garbaged collected. As such, even if the `Thread` object that corresponds to it is unreachable is unreachable, it won't be garbage collected. I believe UI elements register themselves to the UI thread, so the same applies to them. – Sotirios Delimanolis Aug 13 '15 at 02:17
  • I think the non-accepted answers provide more relevant information than the accepted one. – Sotirios Delimanolis Aug 13 '15 at 02:18
  • @SotiriosDelimanolis I get you. So the sub-question concerning active `Thread` is answered. It is simply not ready for garbage collection. I will open a new question asking the behavior of `JFrame` specifically. Hopefully, I could get a definite answer for that. – Lingxi Aug 13 '15 at 02:29

0 Answers0