Junior — Middle
Can you explain what memory leak means in Java and why it occurs?
sobes.tech AI
Answer from AI
A memory leak in Java is a situation where objects that are no longer needed by the program are not released by the garbage collector because there are still references to them. As a result, the memory occupied by these objects is not freed, which can lead to increased memory consumption and eventually to OutOfMemoryError errors.
Causes of memory leaks in Java:
- Long-lived references to objects that are no longer needed (e.g., static collections to which elements are added but not removed).
- Internal caches that are not cleared.
- Listeners or callbacks that are not unsubscribed and hold onto objects.
Example:
List<byte[]> list = new ArrayList<>();
while(true) {
list.add(new byte[1024 * 1024]); // constantly adding objects to the list
}
In this example, the list keeps growing, and objects cannot be garbage collected, leading to a memory leak.