Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

performance - Java Collections and Garbage Collector

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The actual Sun-implementation for Java copies from time to time all referenced/living objects. The space from which was copied can then be used again for memory allocation.

That said your examples damages actually performance. listRubriques.clear() is unneeded (except you hold somethere else a reference to it), because everything referenced by listRubrique is garbage the moment listRubriques is no longer referenced. listRubriques = null may also unneeded if the variable listRubriques go out of scope afterwards (possibly because it's a local variable and the method ends here).

Not only the call to clear is unneeded, as clear accesses the memory of the object that is afterwards no longer in use, the object is accessed and modern processors will put it into their cache. So a dead object is explicitly going to the processor-cache - some possibly more useful data will be overwritten for that operation.

This article is a good reference to get more informations about the Java Garbage collector.

EDIT: To react on the edit in the question: The Garbage collector (the implementation used by Sun at least) is starting from some root references and copies all objects it can reach from this references and that are referenced by the copied objects. So your circular referenced objects are garbage, as no 'outer' reference is pointing to them and the memory will be reclaimed in the garbage collection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...