2

Suppose that, in Java, you have an array of objects that can point to each other. When the array goes out of scope, is the whole thing garbage collected, even though the elements reference each other?

user442920
  • 857
  • 4
  • 21
  • 49
  • Arrays, like other objects, don't go out of scope. Local variables go out of scope. And yes, it's eligible for GC, assuming those are the only references. –  Feb 14 '14 at 22:55

2 Answers2

3

The Garbage Collector actually works out what is reachable and then disposes of everything else, rather than the other way around.

As you've realised a "reference counting" approach falls down as soon as you have circular references.

There is a full description of Java GC here: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Tim B
  • 40,716
  • 16
  • 83
  • 128
2

Yes. The garbage collector is smart enough to know the whole linked list is eligible for garbage collection.

Asaph
  • 159,146
  • 25
  • 197
  • 199
  • What's more, it does not even look at all those inter-garbage references. –  Feb 14 '14 at 23:01