0

I have a doubly linked list of objects:

class MyObject {
  MyObject previousObject;
  MyObject nextObject;

  // Other fields and methods
}

Only the first object of such a list is directly stored in the application, the other objects are reached through this first object and temporarily used in the application (but no permanent references are kept outside the list itself).

When one does not refer to an object anymore, it is collected by the Garbage Collector.

But, I was wondering whether this is still the case, because the (first) object is still being referenced by the 'next object' in the linked list? And what about the rest of the list, are those objects also collected (even though being referenced by each other)?

Note: I know that I could remove all references in the list when I do not use it anymore. But this is 'hard' due to the nature of the application and results in additional (unnecessary?) overhead.

Veger
  • 37,240
  • 11
  • 105
  • 116

3 Answers3

4

The GC doesn't use reference counting, so circular dependencies are handled just fine. You don't need to do anything, and the whole list will be garbage collected when no element of the list is reachable anymore.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

If none of the objects in the linked list is not connected to any live root than the entire list will be collected. See What are the roots?

Community
  • 1
  • 1
Dror Bereznitsky
  • 20,048
  • 3
  • 48
  • 57
1

The critical point is that the first sweep of the GC gathers references to all objects that are reachable. It then discards everything else. In that way it can handle cyclic references and huge self-referential structures like trees without extra work.

Obviously it is much more complicated than that.

Interestingly though - in your scenario where the first item in the list is unreachable but in addition if the third item was reachable then, if it was a LinkedList the first two items would be discarded. With an ArrayList however - previous elements would probably remain.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • In the case that only the third item is reachable, I suppose the first and second ones are not discarded, as the are also reachable through the `previousObject` field of the third (and second) item...? – Veger Feb 18 '13 at 09:37
  • @Veger - There is no `previousObject` method to an object as far as I know. N'or is there a `previousObject` to a Java `LinkedList` but I see your point - if this was some implementation of a back-linked list and somehow the links were built into the objects rather than the list nodes then yes, holding one entry of a list might withold the whole list from GC. – OldCurmudgeon Feb 18 '13 at 10:37
  • It is available in my doubly linked lists, see my code snippet in my question – Veger Feb 18 '13 at 10:38