2

I thought that an object is eligible for Garbage Collection once it is not referenced by any other thing (object or variable). ref : https://stackoverflow.com/a/13144938

But In Java linked list source code

enter image description here

Here not only the author removes any references to it, but he also goes on to remove what it refers to . Why is this needed ? Am I missing something in my understanding about Garbage Collection ?

Community
  • 1
  • 1
Harish Kayarohanam
  • 3,886
  • 4
  • 31
  • 55
  • 1
    [`unlinkLast()`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/LinkedList.java#LinkedList.unlinkLast%28java.util.LinkedList.Node%29) has a similar quirk: `l.prev = null; // help GC` – shmosel Jan 11 '17 at 22:40
  • Say that more than one element is removed through repeated calls to `unlinkFirst()`. The garbage collector *could* collect them all, but it does quite an effort (in the so-called train algorithm) to keep track of which objects are eligible for collection in such cases. My guess is it’s easier and hence less costly to collect them one at a time without caring about references from other eligible objects. – Ole V.V. Jan 11 '17 at 23:10
  • 3
    This _isn't_ needed. – Louis Wasserman Jan 11 '17 at 23:12
  • 2
    Possible duplicate of [Why isn't LinkedList.Clear() O(1)](http://stackoverflow.com/questions/5161031/why-isnt-linkedlist-clear-o1) – shmosel Jan 11 '17 at 23:15
  • See also: http://stackoverflow.com/a/32513361/1553851 – shmosel Jan 11 '17 at 23:16
  • 2
    @LouisWasserman Are you disputing the source, or nitpicking the question? – shmosel Jan 11 '17 at 23:22
  • 1
    Not only is it not needed, it has no effect. `f` itself can be garbage-collected anyway once there are no reachable references to it, and the former value of `f.next` is still reachable via `next` and subsequently `first`. It *might* make the internal workings of GC slightly more efficient, but it is formally redundant. – user207421 Jan 11 '17 at 23:31

1 Answers1

1

The main purpose of setting null is to trigger earlier GC.

See, some objects could be in an old generation and if they point to objects in a new generation VM cannot reclaim those new object till full GC. VM even might be forced to propagate young objects to a long-lived object storage (eden => survival, or survival => tenured).

Minor GC might occur each second, major GC each 10 minutes. Holding an object for 10 minutes could be a dumb thing to do.

Resetting links via null sometimes serves for documentation purposes, like in C we write (void) printf(...); to denote we ignore return value.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303