Search code examples
javaarraysmemoryramallocation

Java - unreferenced arrays still take up memory


I'm currently working on optimizing my application and I noticed that it takes up nearly 1 gig of RAM. I did some profiling and found the problem: I was allocating a lot of memory by creating int arrays holding pixel data in a texture class I made. But this confuses me, because when creating a new array the old array is not used anymore and there is no reference to it anywhere.

I've written a test program that reproduces this problem:

public class Main {

    static class ArrayHolder {
        int[] array;

        void init() {
            array = null;
            array = new int[4000];
        }
    }

    public static void main(String[] args) {
        ArrayHolder holder = new ArrayHolder();
        for (int i = 0; i < 1000000; i++) {
            holder.init();
        }
        System.out.println(holder.array.length);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

When I run this code the program uses up 600 megabytes of RAM. I don't understand why, because when calling the init() method in ArrayHolder the array field is set to the new array and the reference to the old one is lost. Wouldn't that mean that it doesn't take up space anymore? I'm sorry if this is a noobish question but can someone explain why this is and what I'm doing wrong here?


Solution

  • array is a reference to an array in Java. In this respect they are like any other regular object derived from java.lang.Object. Once there are no more references to an array, it is scheduled for garbage collection, which need not happen immediately.

    It's unlikely that this latency in releasing memory will cause you trouble: the garbage collector will collect unreferred objects when it needs to.

    Note that even if the garbage collector does run then there is still no guarantee that the process will hand the memory back to the OS, or the OS will grab the memory back from the process.