6

Effective Java: Item 6: Eliminate obsolete object references.

Generally speaking, whenever a class manages its own memory, the programmer should be alert for memory leaks. Whenever an element is freed, any object references contained in the element should be nulled out.

I don't think I fully understood the description.

What are the examples of a class managing its own memory - I can think of array, list, maybe map.

Could anyone explain the item in somewhat more details it is there in the book? Thanks

Atul
  • 2,673
  • 2
  • 28
  • 34
  • 1
    I think you just need to read the entire section. It's explained very clearly. Just taking that paragraph out of context is actually pretty misleading. – user207421 May 31 '11 at 05:44
  • 1
    @EJP I read the section. I understood what was wrong in the given example. However I am not able to visualize many such situations. So I guess I did not completely understood it. – Atul May 31 '11 at 05:46
  • 2
    There aren't many such situations. Stack and ArrayList are two of them. – user207421 May 31 '11 at 05:56

2 Answers2

4

One simple example is ArrayList, where, when an element is deleted from the end of the list it has to null the array element, not simply decrease the "last element" index. Otherwise the object removed remains reachable by the ArrayList.

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
  • Yes. Lists, array and possibly maps can be such cases. Thanks for the answer. Will accept it as correct if I don't get a better answer till tomorrow. – Atul May 31 '11 at 08:35
1

It maybe speaking about programming your own classes as well as the other answer. So for instance if you have a class that manages memory or resources, then you need to make sure you release the memory or resource when the class is destroyed. A good example of this is if you have a class that manages a connection to a database. The connection would have to be closed to release the resource before your class is destroyed.

ColWhi
  • 1,077
  • 6
  • 16