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:
When a node is created, I'll look up in some table if that node already exists. If so, I'll return a pointer to the old one. Otherwise, make anew node.
Overloaded C++ methods like copy constructors and destructors will do ref-counting, and when the ref-count of a node drops to 0, the node is evicted from the above-mentioned table. (C++ will also free the memory.)
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?
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.
When a node is created, you look up in some table if that node already exists and if so just return a pointer to the old one, else make the new node.
Making this look-up mechanism in Java is not that difficult. Just use a factory method, which checks a 'table' and returns that same instance if it already exists.
I need the reference counting so I know when to evict a node from the table (so it can be garbage collected)
For that Java has the WeakReference
class. It does not allow you to do reference counting, but allows the object to be GC-ed when nobody references it anymore.
Combine these 2 and you can
WeakReference
sCollection
implementations which uses WeakReference
s (for example a WeakHashmap
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With