MyEyesAreSquinty
MyEyesAreSquinty

Reputation: 183

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?

Upvotes: 3

Views: 403

Answers (3)

Ling Zhong
Ling Zhong

Reputation: 1804

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

Upvotes: 2

CollinD
CollinD

Reputation: 7573

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.

Upvotes: 3

Eran
Eran

Reputation: 394126

Assuming you modify the LinkedList in a way such that there are no more references to node2, the garbage collector can release its memory. In other words, node1.next = node3; should be enough, assuming there are no other references to node2.

Upvotes: 1

Related Questions