Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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?

like image 257
Joseph Victor Avatar asked Sep 14 '12 17:09

Joseph Victor


2 Answers

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.

like image 80
Denys Séguret Avatar answered Sep 22 '22 16:09

Denys Séguret


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

  • construct a 'table' populated with WeakReferences
  • use one of the available Java Collection implementations which uses WeakReferences (for example a WeakHashmap)
like image 33
Robin Avatar answered Sep 21 '22 16:09

Robin