Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How does automatic garbage collection work for LinkedList?

In C++ you need to manually delete nodes in the LinkedList:

  Node* node1 = new Node(s);
  Node* node2 = new Node(s);
  Node* node3 = new Node(s);

  node1 -> next = node2;
  node2 -> next = node3;

  //remove node2 by: 
  delete node2;
  node1 -> next = node3;

For Java (it's my first 2 days learning it) how does automatic garbage collection know when to take action? Would:

    node1.next = node3;

be adequate?

like image 789
MyEyesAreSquinty Avatar asked Sep 01 '26 22:09

MyEyesAreSquinty


2 Answers

An object in java will become eligible for garbage collection once no references to it are in scope.

So if you have a singly linked list like so

(1) -> (2) -> (3)

And assume head = node 1

Then yes, setting head.next = head.next.next will allow node 2 to be GC'd at some point.

However, in your example, your node2 could not go away until you explicitly declare

node2 = null in addition to node1.next = node3 because the reference as node2 would keep it in scope.

Note that node2 = null is not actually doing ANYTHING to the Node object that node2 used to point to. Instead it simply sets the reference (since all objects in java are really pointers) to null.

like image 60
CollinD Avatar answered Sep 03 '26 13:09

CollinD


The Java garbage collector PERIODICALLY runs through the entire object reference map to find and delete objects that are unreferenced or cyclically referenced. You can hint the JVM to start an iteration of garbage collection, but there is no way for you to pragmatically instruct the JVM to garbage collect deterministically.

in your case

node1.next = node3;

would be adequate as node2 will no longer have any objects referencing it

like image 37
Ling Zhong Avatar answered Sep 03 '26 12:09

Ling Zhong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!