This question was posted here:
Http://topic.csdn.net/u/20090408/13/89c22659-e194-488d-add1-23256b22465e.html? Seed = 2029607558
Although it is a C # technical topic, it is fully applicable to Java.
But none of them are correct and complete.
The following is my answer. I am confident that this is the true answer, unless the JVM and CLR specifications are modified again.
Normally, after an object is generated, the object is automatically set to OBJ = NULL;
No effect, but no harm (ProgramAttackers are ignorant of the compiler andCodeLooks naive)
The compiler knows more about where the object has lost reference than you do.
Object o = new object ();
Stmt1;
O. XXX ();
Stmt2;
Stmt3;
O = NULL;
In fact, after the compiler is O. XXX (), it will know that it (the object that the original O points to) is recoverable,
It is more accurate than O = NULL after two statements!
When do I need o = NULL ;?
O = NULL; sometimes it is necessary to save the object in the underlying container and pop out the external encapsulation class.
For example, a queue uses an array of member variables to store objects.
Class myqueue {
Private object [] arr = new object [100];
Private int tail;
Private int head;
Private int count;
............;
}
When an element is pressed:
If (count> = 100) throw an error with no space
This. Arr [This. Tail] = O;
Tail = (tail + 1) % This. Arr. length; // start from the beginning if the array ends.
Count ++;
But when it appears:
If (count <= 0) return NULL;
Object o = This. Arr [This. Head];
This. Arr [This. Head] = NULL;
This. Head = (this. Head + 1) % This. Arr. length;
Count --;
This. Arr [This. Head] = NULL; in this case, how does one not actively set null? After this object is pop out
There is always a reference in arr pointing to this object so that the object cannot be recycled. If you just temporarily put an object
In the queue, pop is used immediately. You thought it could be recycled after use, but because there is
Reference points to it. If this reference is not replaced by other elements, the original object cannot be recycled.
If there are similar underlying containers and external packages that hold multiple references to an object at the same time, after you use this object
You should manually set other references pointing to it to null. In other cases (when there is only one normal reference), it should not be set to null.
(Completely redundant)
In fact, the above situation is equivalent:Object o = new object ();
O1 = O;
O. XXX (); // when it is used up, it means that I know that O1 does not need to operate on this object.
// I originally wanted the object to enter the recoverable state at this location, but because O1 is not out of scope,
// Therefore, it cannot be recycled, so you must manually set O1 = NULL;
// This object will be recycled.
}
}