In Java development, we often encounter memory leaks. So why is there a memory leak and how to prevent it!
Memory leak definition: Objects have not been used by the application, but the garbage collector is not able to remove them because they are still being referenced.
Why there is a memory leak. In this example, thea object refers to the B object, and the life cycle of thea object (T1-T4) is much longer than the life cycle (T2-T3) of the B object. When the B object is not used by the application, theA object is still referencing the B object. In this way, the garbage collector is not able to remove the B object from memory, which can cause memory problems, because if a references more such objects, there will be more unreferenced objects and consume memory space.
The B object may also hold many other objects, and those objects will not be recycled by the garbage collector. All of these objects that are not in use will continue to consume the allocated memory space before they are consumed.
How do I prevent memory leaks from happening?
Here are a few easy tips to help you prevent memory leaks from happening.
- Pay particular attention to some collection objects like HashMap, ArrayList , which often cause a memory leak. When they are declared as static , their lifetime is as long as the application.
- Pay particular attention to event snooping and callback functions. When a listener is registered while it is in use, it is not unregistered after it is no longer in use.
- "If a class manages its own memory, developers have to be careful about memory leaks." "Usually some member variables refer to other objects, which need to be empty when initializing.
How to prevent memory leaks from occurring in Java