Petr Shypila
Petr Shypila

Reputation: 1509

Object's references in Java

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?

Upvotes: 0

Views: 131

Answers (2)

MByD
MByD

Reputation: 137412

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)

Upvotes: 1

yams
yams

Reputation: 952

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.

Upvotes: 1

Related Questions