06 February 2011

[Tech notes] How to delete objects in Java?

There is no delete or free keyword in Java. The only thing that can collect the unreferenced memory chunk is garbage collector (GC). To take advantage of that, the best practice is to 'null' out your object reference whenever you want the GC to free that object:


MyObject a = new MyObject();

... /* Do something with object a */

a = null; /* Tell GC to free the memory referenced by a! */

No comments: