Two object references point to each other

In object C, it is likely that two different links may point to each other.

But is this possible in Java? I mean, can two object references refer to each other? If possible, when are they going to collect trash?

And, in the case of nested classes, two objects (inner class and outer class) are related to each other - how are these garbage objects collected?

+7
java
source share
3 answers

I assume you are talking about circular links. The Java GC considers garbage objects if they are not accessible through a chain starting at the root of the GC. Although objects can point to each other to form a loop, they still qualify for the GC if they are cut off from the root.

There are four types of GC roots in Java:

  • Local variables are supported on the stream stack. This is not a real virtual object reference and therefore not visible. For all purposes and tasks, local variables are the roots of the GC.

  • Active Java threads are always considered living objects and, therefore, are the roots of the GC. This is especially important for local flow variables.

  • Static variables refer to their classes. This fact makes them de facto GC-rooted. Classes themselves can be garbage collected, which will delete all referenced static variables. This is of particular importance when we use application servers, OSGi containers, or class loaders in general.

  • JNI references are Java objects that native code created as part of a JNI call. Objects created in this way are specially processed because the JVM does not know whether it refers to its own code or not. Such objects are a special form of GC root.

You can also read here for more information.

enter image description here

+24
source share

Yes you can do it. Like this:

class Pointy { public Pointy other; } Pointy one = new Pointy(); Pointy two = new Pointy(); one.other = two; two.other = one; 

This is garbage collected when both objects are not sharpened by anything other than the other, or by other objects that are “inaccessible” from the current current code. Java garbage collectors "trace" garbage collectors , which means that they can detect such a problem.

Conversely, reference-counted systems (for example, Objective-C without its “modern” garbage collection - I don’t know what the default value is) usually cannot detect such a problem, so objects can be skipped.

+4
source share

Of course, objects can refer to each other. You can simply pass the this pointer in both objects to each other, which is absolutely true.

However, this does not mean that objects are still accessible from the root of the GC. Think of it as a (graphic) tree. If you disconnect a full branch from the trunk, the entire branch will be lost, regardless of how many objects are involved or link to each other.

+3
source share

All Articles