Search code examples
javagarbage-collectionweak-referencessoft-referencesphantom-reference

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


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 :)


Solution

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