Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Object references point to each other

Tags:

java

In objective C, there is a chance that two different references can point to each other.

But is this possible in Java? I mean, can two object references point to each other? If it's possible, when are they going to be garbage collected?

And, In case of nested classes, two objects (inner class's and outer class's) are linked to each other - how are these objects garbage collected?

like image 626
Sai Chaithanya Avatar asked Jul 11 '13 07:07

Sai Chaithanya


People also ask

Can two objects reference each other?

Of course you can have objects reference each other. You could simply pass the this pointer in both objects to each other, which is perfectly valid.

What do object references point to?

Object references are passed by value The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.

When two object references refer to the same object the references are called?

alias. Two references are aliases of each other if they refer to the same object.

Which method checks if two references of the object are pointing to the same object?

equals() versus == The == operator compares whether two object references point to the same object. For example: System.


1 Answers

Yes, you can do this. Like this:

class Pointy {
    public Pointy other;
}

Pointy one = new Pointy();
Pointy two = new Pointy();
one.other = two;
two.other = one;

They're garbage collected when both objects are not pointed at by anything other than one another, or other objects which are "unreachable" from current running code. The Java garbage collectors are "tracing" garbage collectors, which means they can discover this sort of issue.

Conversely, reference-counted systems (like Objective C without its "modern" garbage collection -- I don't know what the default is) cannot normally detect this sort of issue, so the objects can be leaked.

like image 138
Calum Avatar answered Sep 20 '22 19:09

Calum