Low Orbit Flux Logo 2 F

Java How To Delete An Object

Step 1 - Do either one of these:

Step 2 - Do either one of these:

Here is an example showing how you can delete an object in Java. Just assign null to the object’s reference and wait for it to be garbage collected.


MyClass obj1 = new MyClass();
obj1 = null;

Here is a similar example. The difference is that you can call the garbage collector immediately. This isn’t always a good idea and also isn’t guaranteed to actually run the garbage collector right away. It just requests that garbage collection be run.


MyClass obj1 = new MyClass();
obj1 = null;
System.gc();

An object is also deleted when the code block it was declared in is left. In this example the garbage collector will automatically delete the object after the while loop finishes.


while( x == 5 ) {
    MyClass obj1 = new MyClass();
}

Multiple References

Before an object can be removed all references to it need to be removed. Basically the reference count needs to be zero. See the example below.


MyClass obj1 = new MyClass();  // create an object
obj2 = obj1;                   // new reference created
obj1 = null;                   // remove one reference ( not enough )
obj2 = null;                   // remove the other reference

Avoiding Memory Leaks

Java does a pretty good job of preventing memory leaks but they can still occur. If you keep a reference to an object when it is no longer used it will still be taking up memory. One instance where this can be an issue is if you have a long running piece of code.

In this example we declare an object and an array. Both of these take up memory. Once we have computed our results from both of these they are no longer needed. We assign them both to null so that they can be garbage collected. Otherwise they wouldn’t be deleted until after the long running ( potentially infinite ) while loop completes.


public void methodOne() { 

    MyBigClass x = new MyBigClass();    // class that uses up memory
    int data1[] = new int[34000000];    // array that uses up memory

    int result1 = compute(data1);       // don't need data1 after getting result
    int result2 = x.getResult();        // don't need x after getting result

    x = null;                           // remove 
    data1 = null;                       // remove

    while( x == 5 ) {                   // might run forever
        process_input();
    }
}