简体   繁体   中英

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?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM