Causes of memory leaks in Java
As we know memory leak is when program or part of the code/program repeatedly fails to return memory which it has obtained for temporary use. And due to that we end up in exhausted part of the OS and eventually program can no longer function. A small memory leak also can sometimes make a bigger impact on consuming the memory. So I would like to write some of the reasons which causes Memory leaks in java.
First reason would like to mention is the Unknown Object reference :
Unknown Object references
Unknown object references are the objects which are no longer needed by your Java program or application itself but they still have active references from other objects. Due to this fact Garbage Collector fails to reclaim their memory. So it is very important to find these Unknown Object references and remove or free the references dependent on them.
Mutable static objects
Static variables serve as "roots" to the Garbage Collectors because it is held by its class and subsequently by its ClassLoader. So if you do not set the static variables to null then they will live as long as your code is live. The main reason static object memory leak can cause problem is because it can be shared across multiple threads. So we need to be careful while creating the static objects or static collections.
Wrong use of equals/hashcode
If equals/hashcode methods violate the equals contract it will lead to memory leaks when it is used as a key in a map. So you have to be very careful if you want to have your own object without a valid hashcode implementation as a key in a map, because different hashcodes for equal objects can lead to memory leak.
Over riding finalize method
We often override the finalize() method to free the system resources, before actually our garbage collector clean up. But finalize() method do not guarantee that it will run or not, so it leads to memory leak as garbage collector might not pick that object where finalize method has not run.
If you like to add or know more, please add it comments.