Senior
What is a memory leak?
sobes.tech AI
Answer from AI
Memory Leak — a situation where a program continues to occupy memory that is no longer needed and not used, but is not released.
In Java, a memory leak can occur if objects remain reachable (for example, through references in collections), even though they are no longer needed, and the garbage collector cannot delete them. This leads to a gradual increase in memory consumption and can cause an OutOfMemoryError.
Example of a leak:
List<byte[]> cache = new ArrayList<>();
void addData() {
byte[] data = new byte[1024 * 1024]; // 1MB
cache.add(data); // objects remain in the list and are not removed
}
If the addData method is called many times, memory will grow because objects are not removed.
To prevent leaks, it is important to:
- Remove unnecessary references
- Use weak references (WeakReference) when necessary
- Monitor the lifecycle of objects
- Profile the application for memory usage