3 ms·
There are a lot of answers here and on Stack Overflow that are a lot more complicated or esoteric than they need to be. The simplest example in my mind is a vec
by mcculley 10y ago
There are a lot of answers here and on Stack Overflow that are a lot more complicated or esoteric than they need to be. The simplest example in my mind is a vector of references (e.g., java.util.Vector, java.util.ArrayList). In the implementation of removing a tail element or truncating the vector, one must set the removed references to null, otherwise the objects they point to cannot be collected and yet they are unavailable to users of the vector.
- jdmichal 10y agoI'm not quite sure where you're getting that interpretation... Of course, any removed element must have its reference replaced with `null`, because otherwise that's a live reference. This is true for any object, not just collections. Your program not being able to reach it is a function of the interface, not the object. I think that a separation needs to be made between purposefully and unpurposefully unreachable or retained references. For instance, it's perfectly valid for a method to return one of two internal references based on a boolean flag. So both those objects are still reachable, even if only one reference is "purposefully" reachable at once. That isn't a memory leak; it's just programming logic.
- mcculley 10y agoOne can implement a class with an interface like java.util.List and have remove() just decrement an internal counter when the item to be removed is at the end of the list. This would be a correctly functioning implementation. One must go further and set the reference to null to prevent a leak.
- jdmichal 10y agoMy point is that it's only a "leak" because the List interface makes it clear that the program no longer intends to reach that object. So this would be "unpurposefully reachable" -- The program did not intend for the object to be reachable, but it is. This has nothing to do with the List interface, and everything to do with how a interface is used and what intent that usage proves.
- mcculley 10y agoI think we are arguing over the definition of "leak". When you have one developer producing a data structure used by another developer, this kind of leak is an easy mistake to make. I think in the sense of answering the Stack Overflow question, that makes it a more useful answer than the examples about ClassLoaders and non-heap resources.