问题
duplicate - How to destroy java objects?
My question is very simple. I am new to app development with Java and am not sure whether I need to null objects after i am finished with them. for example i am using libGDX to create a game and I have several objects (Actors) being created. when I am finished with them do I simply call
obj.remove();
or should i -
obj.remove();
obj = null;
do I save memory by nulling objects or is there no advantage to be had?
回答1:
Generally, in java, marking the Object references as null
is done to make it explicitly eligible for GC. If an object is unreachable, then it becomes eligible for GC, so, yes, you can mark it as null and let the GC do its work.
The Object will become unreachable only when there is no reference pointing to it.
example :
class MyTest {
@Override
protected void finalize() throws Throwable {
System.out.println("object is unreachable..");
}
}
// In some other class
public static void main(String[] args) {
MyTest o1 = new MyTest();
MyTest o2 = new MyTest();
System.gc();
o1 = null;
System.gc();
System.out.println("hello");
}
O/P:
hello
object is unreachable..
Here, you might have several thousand lines of code after "hello". You might want to make the GC's job easier by marking the object's references as null.
回答2:
No you do not need to null or manually delete objects. The java garbage collector will do this for you for any objects that have no pointers referencing them (when an object goes out of scope for example).
回答3:
Manually nulling Objects in Java is bad, because it is slowing down most garbage collection (GC) algorithims. The GC detects by itself wether an Object is reachable or not and then it gets removed. After nulling an object the space in memory is still used and only after the GC recycles the space it can be used again. So nulling objects does not free up your space immediately. Also starting the GC manually is a bad idea. It is started by the VM if it is needed.
来源:https://stackoverflow.com/questions/25905901/do-you-need-to-null-objects