Aryaman Kumar
Aryaman Kumar

Reputation: 68

Will Java garbage collector run?

Node class is given as follows:

// I have not added class modifiers for simplicity
class Node{
 
 int data;
 Node next;

//Constructor
Node(int data){
  this.data = data;
  next = null;
  }
}

Suppose I have a simple linked list of numbers n1 , n2 , n3 etc (it has atleast 2 nodes). We can reference linked list only using head pointer. Head pointer points to n1 node. Now there is a delete node function where we pass head node.

Node deleteNode(Node head){

  if(head==null)
   return null;
  
 else
   return head.next;
  
}

Suppose we run delete Node function one time. Will garbage collector of java, deletes n1 node , because now we cannot access it but still node n1 points to n2 (in delete Node function we have not made "next" parameter pointing to null)? We have just changed head pointer.

Upvotes: 1

Views: 68

Answers (2)

Henya14
Henya14

Reputation: 86

An object will be garbage collected if there are no reachable references to it.

For example if you initialize your linked list like this:

Node head = new Node(0);
Node n1 = new Node(1);
Node n2 = new Node(2);
head.setNext(n1); //Let's assume that you have the basic getters and setters implemented
n1.setNext(n2);

Then your original head will be flagged for garbage collection if you do this:

head = deleteNode(head); //Here head will be referencig n1, so nothing is referencing the original head anymore, so it will be garbage collected somewhere in the future

(Side note: you don't have to initialize fields of a class to null in the constructor, because they are null by default)

Upvotes: 1

anwait
anwait

Reputation: 11

From your snippet the garbage collector wont run.

Your Node deleteNode(Node head) is not deleting anything, you are simply returning the next node if there is one.

In order for for garbage collector to run you have to discard every reference to an object which is not happening here.

Upvotes: 1

Related Questions