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.
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){
}
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){
}
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)
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.