Remove a variable memory

You can indicate to the garbage collector that an array can be released by assigning null to it:

    int[] a = new int[someSize];
    int[] b = new int[someSize];
    ....
    // I no longer need 'a'
    a = null;
    // ... but I can still use 'b'

However there are a number of things to note:

  • This does not free the space. Rather, it is making the array eligible to be freed by the garbage collector. The GC may not get around to freeing it for a long time.

  • In fact, the array is only eligible for garbage collection if it is not reachable. If you've assigned a reference to the array to another (still live) variable or reachable object, the GC won't reclaim it.

  • There is rarely any point in doing this in real-life Java applications. It is normal practice to simply allow the variables go out of scope in the normal course of the computation1. You would only explicitly null a variable (or object field or array element) like that if the variable is not going to go out of scope for a long time AND it refers to a large array / object or network.

  • It is highly inadvisable to try to force the GC to run by calling System.gc() after assigning the null ... or ever2. If the call has any affect at all, it is likely to be expensive. It is better to let the JVM schedule a GC at an optimal time.


1 - Any reasonable JVM implementation will know that local variables go out of scope when a method exits. Whether the JVM tracks scopes at a finer granularity is implementation specific, and (to be honest) I do not know how JVMs handle this in practice.

Note that just about anything is technically conformant to the JLS requirements .... provided that the GC does not delete reachable (i.e. non-garbage) objects. That includes a JVM that uses the Epsilon no-op GC, which never collects garbage and terminates the JVM when it runs out of space.

2 - The only legitimate reasons are: 1) testing the behavior of GC related functionality; e.g. finalizers, reference queue processors, etc, or 2) avoiding harmful GC pauses in a real-time application; e.g. running the GC when changing "levels" in a real-time game.


Stephen C has answered your question though for non primitive type you would also like to ensure that all objects inside your array are marked as null if you dont need it, this will ensure that you dont have memory leak.

Something like:

for(Object obj : myObjectArray){
  obj = null;
}

then make your array reference null

myObjectArray = null;