Frage

I have an Object that occupies a large chunk of memory, I pass the object into a static helper method for processing. What does the JVM do with the Object after the method returns?

public class Helper {
    public static boolean processObject(Object object) {
        // Do something with object
        return true;
    }
}

Usage:

Object object = new Object(); // large object created
if (Helper.processObject(object)) {
    // do something
}

My concern is that the large object will stick around in memory for longer than if it was processed in the same class.

War es hilfreich?

Lösung

It will stick around as long as there is still a reference to it. Once the last reference goes out of scope it can be garbage collected (but it won't nessissary be collected immediately). I have expanded your example to more clearly demonstrate

public static void main(String[] args) {

    int[][] largeArray=new int[1000][10000]; // large object created

    use(largeArray);

    //object still retained

    while(true){

    }

}

public static void use(int[][] in){

}

enter image description here

This is usually fine. But you could allow it to be collected earlier by not holding on to the reference at all

public static void main(String[] args) {


    use(new int[1000][10000]);

    while(true){

    }

}

public static void use(int[][] in){

}

enter image description here

Equally explicitly nulling out the variable would also allow it to be collected earlier.

public static void main(String[] args) {

    int[][] largeArray=new int[1000][10000];

    use(new int[1000][10000]);

    largeArray=null;

    while(true){

    }

}

Usually this isn't worth worrying about, but if the other code is in a long loop it might be (although thats probably a sign you need to refactor your code)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top