Reset any object reference as soon as the object is no longer needed? Once an object no longer refers to it, GC can assemble it, but I assume you already knew that. GC can also work on raw object graphs (if A has a single link to B and there is no longer a link to A, then you can collect A and B).
It makes no sense to call System.gc (), because if the JVM needs more memory, it will do it on its own, and then use the free memory. If it cannot free up more memory, then you run into OOME.
Now the default heap size is not so large, and therefore quite often a larger heap size is required.
Creating objects in loops is not a particularly bad example, and in many cases it is very relevant. What should be avoided is to repeat an instance of one object in a loop. As a rule, string concatenation should be avoided in loops and replaced with a StringBuilder created outside the loop, since it is much less efficient in terms of performance, but not in terms of memory.
Not sure if I really answer your question.
source share