I’ve searched for this but can’t seem to find a straight answer for this.
Basically I have some code that creates a copy of an array(using Arrays.copyOf to create int[]), and it does some work and either outputs the results or sends the Arrays.copyOf to a queue for further processing.
If I change the copyof my results are no longer correct so I think I need it but I’m wondering if there’s something I can do after its done because, as per my memory profiling, its taking up all my memory and garbage collecting helps but it just builds up again. I’m really not sure if this will help but I wanted to test to see if my program functions as it did with a smaller memory footprint if I somehow delete the int[] after submitting it to a queue.
I’m new to Java so if this logic is totally flawed, is there another way to achieve the same result? Bottom line is I’m creating a new array its being used a bit but lingers around when no longer needed(it takes 15G of my max memory, then I believe garbage collector comes in and reduces it but it shots back to max within a few seconds again). Maybe can I set the variable to null or something once I’m sure its not needed(the objects I’m copying are quite large)?
Here’s some code just to show what I mean(its kind of crappy but hopefully it lets you understand how its setup in the code, all this is within a multithreaded callable):
while(!queue.isEmpty()) {
int[] data_list = Arrays.copyOf(current.list, current.list.length);
if (things work) {
Sysout("print results");
} else if (current.k > 0) {
queue.add(new Queue(data_list));
}
}
}
In general, the thing to do here is “trust that the garbage collector knows what it’s doing.” The JVM is very good at figuring out when objects aren’t needed any more, especially e.g. if it can prove that an object doesn’t “escape” the method where it was created.
Java doesn’t even provide a way to delete the memory being used by an object, except eliminating all references to it — which is exactly what you’re doing.