0

I'm have one question.

I have class Node

public class Node {
    public final Key   KEY;
    public final Value VALUE;
    //Other fields and methods.
}

Method add

public void add(Key key, Value value) {
this.key   = key;
this.value = value;
//Other code
}

And this code:

//something here...
private Node node = new Node();
//Some code
add(node.KEY, node.VALUE);
node = null;

Is there node object will be utilized by garbage collector exclusive KEY and VALUE fields or node object with all another fields will be saved in memory?

Petr Shypila
  • 1,449
  • 9
  • 27
  • 47
  • 2
    Shouldn't the line `public void add(node.KEY, node.VALUE);` be something like `add(node.KEY, node.VALUE);` ? If so, node can be garbage-collected after the `node = null;` line. – nif Jul 01 '13 at 19:30
  • 1
    The Java GC rules works on object graphs and [reachability](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Reachability_of_an_object). Ask yourself: can an object be reached from a [root](http://stackoverflow.com/questions/6366211/what-are-the-roots)? If it *can* be reached from a root then it is considered reachable and is not eligible for reclamation; otherwise, it can no longer be accessed by code and is eligible for reclamation. (There is also strong vs weak reachability, but that's the gist of it.) – Paul Jul 01 '13 at 19:33
  • Nif is right the object is null so it is garbage collected see my answer for more. – yams Jul 01 '13 at 19:37

2 Answers2

1

KEY and VALUE will still have a reference in your program so they will not be garbage collected. But since node has no more references in your program, it is now a candidate for a garbage collection.

To make it clear. node and its fields, excluding KEY and VALUE will be candidates for GC (assuming you didn't assign any other fields to an object that is still present and referred in your program)

MByD
  • 135,866
  • 28
  • 264
  • 277
  • Yes, i know that `KEY` and `VALUE` saving in memory. I'm only was not sure is the `node` object was keeping in memory with all another fields or deleted exclusive `KEY` and `VALUE` fields. – Petr Shypila Jul 01 '13 at 19:31
  • As I wrote, `node` IS a candidate for garbage collection. – MByD Jul 01 '13 at 19:33
1

Basically if a object has a reference regardless of whether it is a strong reference or a weak reference it will not get garbage collected. The only way to get these objects garbage collected is to null the object at any time.

public class Node {
    public final Key   KEY=null;
    public final Value VALUE=null;
    //Other fields and methods.
}

Just make sure they get initialized before being called.

As far as node is concerned because you set it null in the last line it will get garbaged collected. Setting an object null removes reference therefor it is a null object and is garbage collected nothing is in the memory.

yams
  • 942
  • 6
  • 27
  • 60