Reputation: 7458
I wonder when Garbage Collector releases the memory associated to a deleted node from a LinkedList!
I mean the GC releases the memory simply because there is no reference to that object? ( with reference to the code below please)
public class Node {
int data;
Node next;
public Node(int data){
this.data = data;
}
public Node(Node node){
data = node.data;
next = node.next;
}
}
public void delete (Node prevNode, Node currentNode){
if (currentNode == tail){
tail = prevNode;
}
if (currentNode == head){
head = currentNode.next;
} else {
prevNode.next = currentNode.next;
}
len--;
}
Upvotes: 1
Views: 746
Reputation: 11061
The garbage collector periodically checks for unreachable objects, such as your deleted node here (assuming there are no other references.)
Precisely when it does this is subject to a lot of conditions, since there are multiple garbage collector implementations that use different timing strategies. In general you cannot predict when.
If you need to eagerly release some resource on delete(for example, perhaps your linked list node has an associated file descriptor), you are better off doing it yourself before dropping the last reference.
If you need to monitor when your node has been handled by the garbage collector, you should look at the classes available in the java.lang.ref
package, particularly the ReferenceQueue class.
Upvotes: 1