Shehryar
Shehryar

Reputation: 550

How to Find and Fix Memory Leaks in Nested Classes in Java?

I'm finding the concept of memory leaks within inner classes fairly difficult to grasp. Most of the answers I find are within the context of java which further confuses a beginner like myself.

Most answers to similar questions here redirected to this: When Exactly is it leak safe to use anonymous inner classes?

Again, the answer here was difficult to get across for someone fairly new to OOP.

My question(s):

  1. Why do memory leaks occur with the inner classes?

  2. When using inner classes, what are the most common memory leaks that can occur?

  3. What are remedies to memory leaks that one can come across frequently?

Upvotes: 2

Views: 1655

Answers (1)

Andreas
Andreas

Reputation: 159114

Why do memory leaks occur with the inner classes?

Because the inner class maintains a reference to the outer class.

If the inner class doesn't actually need that reference, which is quiet common for anonymous classes, and the outer class is otherwise unreachable, it is nevertheless not garbage collectable because of that reference.

That is considered a "leak", i.e. memory that should be freed is not being freed, as long as a reference to the inner class is maintained.

When using inner classes, what are the most common memory leaks that can occur?

See answer to first question.

What are remedies to memory leaks that one can come across frequently?

Use static nested classes instead of anonymous, local, and inner classes. Top-level classes are of course also an option.

This is of course only necessary when the lifetime of the inner class exceeds the lifetime of the outer class.

Upvotes: 3

Related Questions