I am currently making a game. I plan on creating a lot of instances of one class for the projectiles portion of my game. I was just wondering, since I will be creating many instances of this class, and the projectiles will have no use once they have rendered off the screen, is it really ok to just create them? I know there is a garbage collected in java, but how do I actually know that the instances of a class that are not used anymore will get deconstructed? Is this something I should really worry about?
3 Answers
I know there is a garbage collected in java, but how do I actually know that the instances of a class that are not used anymore will get deconstructed?
Every object that has not a variable referencing it (a pointer) is eligible for garbage collection. This of course doesn't mean that it will be destroyed instantly as soon as it's no longer referenced but the Garbage Collector will take care of it and you shouldn't worry.
5 Comments
Java Virtual Machine (JVM) is responsible to invoke finalize method on all unused objects by calling:
System.runFinalization();
or
Runtime rt = Runtime.getRuntime();
rt.runFinalization();
Once, JVM prepare the list of unused objects, it invokes the GC(Garbage Collector) by giving this list of unused objects.
And, if you want to invoke gc manually, use:
System.gc();
Runtime rt = Runtime.getRuntime();
rt.gc();
or use this directly:
Runtime.getRuntime.gc();
Important : But basically, you can't force JVM to invoke the GC. Rather, you can request and this request may or may not clean the memory.
Comments
Mostly it's fine to leave this kind of thing to the garbage collector. However, if you are worried about having loads of mostly-unused objects taking up bits of memory here and there, you could use an object pool. That's where you create a fixed number of objects, keep track of which you are using, and recycle them, so they are confined to one block of memory.
Java. Only worry about closing them it they point to some stream or resource.