cleanup in java
hello...i am an avid fan of java.. i'm currently in a web engineering project. i've heard that there have been various kinds of memory leaks in java.
so my question is, after using user-created objects within a function, is it safer to equating them to NULL? i know this kind of cleanup procedure is a must in C and C++.
Hoping for a favorable response from all JAVA addicts : )
thanks!!
Assigning the user-created objects to NULL will do nothing additional that is not already being catered for.
Java will identify these objects as unused as no other objects will have a reference to them.
Memory leaks tend to arise from keeping old references to objects.
A stupid example would be:
public Class Test {
public static ArrayList heads = new ArrayList();
public Test() {
}
public void process(String[] array) {
String head= array[0];
String first = array[1];
heads.add(head);
head = null;
}
}
In the above example first will be garbage collected but the object identified by head will remain.
Providing nothing is holding a reference to an object, it will be eligible for garbage collection. You don't need to manually free the memory. Leaks come where people do things like forget they've got a reference to an object in, say, a collection. When inside a method, if the object is only used inside that method, it falls out of scope and is eligible for garbage collection when the method returns. It's not necessary to manually assign the reference to null
> Assigning null indicates the garbage collector that
> the object is available for garbage collection.
Not necessarily. I think doing so gives the developer a false sense of completeness, especially to those who don't yet really know the difference beteen "object" and "reference"
> But it is not predictable when actually the object
> will be garbage collected
Absolutely