Classes that manage their own memory

Effective Java: Clause 6: Eliminate obsolete object references.

Generally speaking, whenever a class manages its own memory, the programmer should be warned about a memory leak. Whenever an element is freed, any reference to the objects contained in the element should be excluded.

I do not think I fully understood the description.

What are some examples of a class that manages its own memory - I can think of an array, a list, possibly a map.

Can someone explain this subject in more detail, is it in the book? Thanks

+6
source share
2 answers

One simple example is an ArrayList , where when an element is removed from the end of the list, it should nullify the array element, and not just decrease the index of the "last element". Otherwise, the remote object remains accessible using the ArrayList .

+4
source

Perhaps this is about programming your own classes, as well as another answer. For example, if you have a class that manages memory or resources, then you need to make sure that you free the memory or resource when the class is destroyed. A good example of this is that you have a class that manages a database connection. The connection must be closed to free the resource before destroying your class.

+1
source

Source: https://habr.com/ru/post/889419/


All Articles