NSF
NSF

Reputation: 2549

Will this cause memory leak in java?

This is an interview question but I'm not quite sure about the correct answer. Suppose we have some classes like:

public class A {
    public Object link;
    public A() {
        link = null;
    }
}

Then we create two instances:

A a1 = new A();
A a2 = new A();
a1.link = a2;
a2.link = a1;

Then we release the references:

a1 = null;
a2 = null;

Then the question is: as JVM would use GC mechanism. How would it handle this case? Will it instantly remove the two instances when it runs or just have the memory space signed and leave them alone? What if I have 1 million such instances that form a cycle and have no external references? Will the cleaning makes the GC thread hang?

Upvotes: 3

Views: 247

Answers (3)

Saurabh
Saurabh

Reputation: 7964

As per the current logic of code a1 has a member variable which points to a2 and a2 has ha member variable which points to a1. When you do a1 = null a1 becomes eligible for getting GCed. Same is case with a2. Now when GC runs then it tries to see what all objects are reachable starting from root and even though these two refer each other they become unreachable in chain starting from root (case of isolation) hence they get garbage collected without any issues.

Upvotes: 0

corsiKa
corsiKa

Reputation: 82579

The objects themselves can reference eachother with as many links (one million cycles as you mention) as you want. If there is no 'route' back to a thread, the objects are eligible for garbage collection, no matter how many other garbage eligible nodes they connect to.

Now this does not mean they WILL get collected, only that they're eligible. So if your garbage collector decides not to process them, then I suppose that could be considered a memory leak. You can't guarantee they'll disappear.

Upvotes: 3

maerics
maerics

Reputation: 156434

Cyclical references may cause memory leaks for naive implementations of certain garbage collection strategies such as reference counting. (Which is not to say that reference counting is naive but that poor implementations may suffer from the problem.)

However, this problem is well known to people who implement GCs and it can be avoided. Moreover, most modern JVMs use generational garbage collectors which typically do not suffer from such problems.

Upvotes: 2

Related Questions