is there a way to recycle a complex java object once the GC has decided it is unreachable

1.9k views Asked by At

In C++ I use reference counted objects to impplement a for of "auto" recycling object pool

SmartPointer<ObjType> object = pool.getObject(); // hold reference

// ... do stuff with object over time.

object = nullptr; // that is when reference 
                  // count goes to 0

-- Now I have on the C++ objects an "onFinalRelease()" method which gets called when the refcount reaches 0. I can overide this ( default is delete(this) ) to auto-recycle objects rather than destroying them.

The question is can I implement this pattern with some combination of java reference types and reference pools. Of course this is for a type of large complex expensive to create object where it makes sense. That is I want to do:

SomeReference r = referenceQueue.getReference();

pool.recycle(r.takeBackUnusedObjectFromGC()); // ??????????????????????????

This would be real nice :)

4

There are 4 answers

7
Tom Hawtin - tackline On BEST ANSWER

You can use PhantomReferences to do something like this. Have an interface (proxy) object with a (strong, unidirectional) reference to the expensive object. Also keep a strong reference to the expensive object in your pool management. Keep a PhantomReference to the interface object. Once the PhantomReference comes up on its ReferenceQueue you know for sure that the expensive object is not being used through an interface object (even allowing for finalisation). The expensive object can now be reused with a new interface object.

However, it probably isn't worth it.

3
Edward Dale On

Java has something similar called the finalize method. Unfortunately, once it runs for an object, there's no going back. In addition, it's not even guaranteed to run.

You best bet might be to create a pool of objects and track yourself whether they can be reused or not. Apache Commons Pool might be useful for this.

3
Russell Zahniser On

With reference counting, there is a clearly defined time when an object becomes garbage - when the reference count goes to zero. With Java's garbage collection, there is no guarantee that a given object will ever be garbage collected, even if there are no more strong references to it.

Implementing your own reference counter by hand is the best solution I can think of.

0
Pr0methean On