javasmart-pointersrefcounting

Smart Pointers and Ref Counting in Java


I'm trying to write DagNode class in Java whereby two nodes are logically equal iff they are equal as references.

The idea in C++ —(I'm from C++)— would be to use smart pointers and reference counting:

However, there seems to be no way to automatically do ref-counting in Java. I'll need to do ref-counting to know when to evict a node from the table (so that it can be garbage collected), and I really want to avoid calling node->incRef() and node->decRef() at the start and end of each function.

How do we do this C++ idiom in Java?


Solution

  • In Java, the reference survey and the garbage are automatic.

    But that doesn't mean it's entirely hidden.

    You seem to need ReferenceQueue if you want to know when an object can be garbaged, and maybe WeakReference if you want to keep pointers which don't prevent the garbage.

    I suggest you have a look at the description of the java.lang.ref package to find the best solution for your need.