-1

A class like LinkedList stores objects in instances of an internal class called Node. Each time a new element is added, a new Node is created with the 'new' operator. Why does not it try to reuse Nodes that were previously created for elements which were later deleted? The LinkedList could store a list of nodes created for elements that were deleted and try to reuse them when new elements are added. Moreover, it could store the unused Nodes under a soft reference so as not to waste memory. Reusing Nodes should reduce the load on the garbage collector and decrease the number of its invocations. Why does not Java do that?

  • 3
    Because those objects can be garbage collected, no longer taking up memory when not needed. The overhead of those objects is fairly minimal (think bytes per entry), and it would complicate the design of those classes if they tried to re-use everything. The CPU overhead of instantiating what is essentially a wrapper object is quite minimal as well, and that tradeoff is likely worth it for the ability to apply OOP principles to the objects you add to the list. Further, these objects define state/relationships between other entries, which would have to exist somewhere. – Rogue Dec 14 '22 at 17:11
  • Storing unused nodes under a soft reference would mean allocating that soft reference in addition to the (unused) node, thereby increasing memory consumption and the load on the garbage collector. – Thomas Kläger Dec 14 '22 at 18:30
  • 2
    The main misconception is in your sentence “*reusing Nodes should reduce the load on the garbage collector*”. A garbage collector has to process the objects that are still alive, hence, reusing objects *raises* the load on the garbage collector. It could decrease the number of GC invocations when the speculative remembering turned out right, however, even then, it won’t compensate the higher costs of the garbage collection. But all unused cached nodes will even raise the number of invocations. – Holger Dec 14 '22 at 18:59

1 Answers1

3

Moreover, it could store the unused Nodes under a soft reference so as not to waste memory. Reusing Nodes should reduce the load on the garbage collector and decrease the number of its invocations.

Java's garbage collection is optimized for the case of having many short-lived objects over having longer-lived objects -- especially for small objects like linked list nodes. Due to the generational approach of Java's GC, it usually performs better to throw away existing objects and reallocate them. Additionally, maintaining soft references can often add noticeable overhead.

The approach you describe would make things worse, not better, for most applications. In general, the Java garbage collector is extremely good at its job, and trying to manually manage Java objects for memory reasons rarely beats it.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413