Question

Let's consider the following 2 cyclic referencing examples:

Straight forward cyclic referencing

class A {        
    B b;        
}

class B {
    A a;
}

WeakReferenceing

class A {
    B b;
}

class B {
    WeakReference<A> aRef;
}

The following SO question answered by @Jon Skeet makes clear that the straight forward example will also be garbage collected as long as no "GC walk" from a known root exists to the cycle.

My question is as follows:

Is there any reason performance or otherwise to use or not to use the idiom represented in example 2 - the one employing a WeakReference?

Was it helpful?

Solution

Is there any reason performance or otherwise to use or not to use the idiom represented in example 2

The Java Reference types have a couple of performance implications:

  • They use more space than regular references.

  • They are significantly more work for the garbage collector than ordinary references.

  • I also believe that they can cause the collection of objects to be delayed by one or more GC cycles ... depending on the GC implementation.

In addition the application has to deal with the possibility that a WeakReference may be broken

By contrast, there are no performance or space overheads for normal cyclic references as you use them in your first example.

In summary, your weak reference idiom reduces performance and increases program complexity ... with no tangible benefits that I can see.


My guess is that this Question derives from the mistaken notion that cyclic references are more expensive than non-cyclic references in Java ... or that they are somehow problematic. (What other logical reason would cause one to propose an "idiom" like this?) In fact, this is not the case. Java garbage collectors don't suffer from the problems of reference counting; e.g. C++ "smart pointers". Cyclic references are handled correctly (i.e. without leaking memory) and efficiently in Java.

OTHER TIPS

The problem is you do not know when GC will clear the weakreference objects.

It may be cleared just as you declare it! GC is very eager to collect it.

Or you can have root reference to the weakreference object to prevent it from the garbage collection.

Or check its status through RegisteredQueue.

It's like finalize method. You do not know when GC will execute this method.

Sources:

http://pawlan.com/monica/articles/refobjs/ http://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top