Smart pointers and reference counts in Java

I am trying to write a DagNode class in Java, where two nodes are logically equal if they are equal to links.

The idea in C ++ - (I'm from C ++) - will use smart pointers and reference counting:

  • When a node is created, I will search in some table if that node already exists. If so, I will return the pointer to the old one. Otherwise, redo the node.

  • Overloaded C ++ methods, such as copy constructors and destructors, will recount, and when the number of node backlinks drops to 0, node is excluded from the above table. (C ++ will also free up memory.)

However, there seems to be no way to automatically do the recount in Java. I will need to do reference counting to find out when to deflate the node from the table (so that I can collect garbage), and I really want to avoid calling node->incRef() and node->decRef() at the beginning and end of each function.

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

+7
source share
2 answers

In Java, background inspection and garbage are automatic.

But this does not mean that it is completely hidden.

It seems you need a ReferenceQueue if you want to know when an object can be garbage, and perhaps a WeakReference if you want to keep pointers that don't interfere with the garbage.

I suggest you familiarize yourself with the java.lang.ref package description to find the best solution for your needs.

+6
source

When a node is created, you look in some table if that node already exists, and if so, just return the pointer to the old one and then create a new node.

Creating this search engine in Java is not that difficult. Just use the factory method, which checks the "table" and returns the same instance if it already exists.

I need reference counting, so I know when to deflate a node from a table (so it could be garbage collection)

For this, Java has a WeakReference class. It does not allow you to do reference counting, but allows the object to be GC-ed when no one else references it.

Combine these 2 and you can

  • build a table populated by WeakReference s
  • use one of the available Java Collection implementations that uses the WeakReference (e.g. a WeakHashmap )
+2
source

All Articles