A little question regarding performance in a Java web app.
Let's assume I have a List<Rubrique>
listRubriques
with ten Rubrique
objects.
A Rubrique
contains one list of products (List<product>
listProducts
) and one list of clients (List<Client>
listClients
).
What exactly happens in memory if I do this:
listRubriques.clear(); listRubriques = null;
My point of view would be that, since listRubriques
is empty, all my objects previously referenced by this list (including listProducts
and listClients
) will be garbage collected pretty soon. But since Collection in Java are a little bit tricky and since I have quite performance issues with my app i'm asking the question :)
edit : let's assume now that my Client object contains a List<Client>
. Therefore, I have kind of a circular reference between my objects. What would happen then if my listRubrique
is set to null
? This time, my point of view would be that my Client objects will become "unreachable" and might create a memory leak?
In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically.
GC Implementations JVM has five types of GC implementations: Serial Garbage Collector. Parallel Garbage Collector. CMS Garbage Collector.
When the JVM doesn't have necessary memory space to run, the garbage collector will run and delete unnecessary objects to free up memory. Unnecessary objects are the objects which have no other references (address) pointing to them.
If you have:
listRubriques = null;
and there are no other objects holding references to listRubriques
or its containing objects, it's eligible for garbage collection. But there is no guarantee about when the JVM will actually run garbage collection on it and free memory. You can call:
System.gc();
to recommend to the JVM that you think running garbage collection at this time is a good idea. But even then, there is no guarantee.
Also having
listRubriques.clear();
before setting listRubriques
to null
is not necessary.
EDIT: To answer your question about circular references, JVMs are smart enough to figure out that the whole object graph is disconnected from any actively running code and the JVM will correctly determine that they are all eligible for garbage collection. This has always been true even in the bad old days of reference counting. Modern JVMs are just faster and more efficient. But they aren't garbage collecting any more objects than older JVMs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With