Exposition:
In general, Reference Counting has the weakness of "it can’t detect loops." However, in some cases, Reference Counting is really useful:
class EmergencyPatient {
DoctorPtr doctor;
EmergencyPatient() { doctor = Doctor::acquire(); }
~EmergencyPatient() { Doctor::release(doctor); }
};
Now, in a reference counted world, as soon as we no longer refer to an EmergencyPatient, the doctor is released.
In Java’s non-refcounted world, this depends largely on when the EmergencyPatient is garbage collected — and since the garbage collector is generational, the EmergencyPatient can be in an older generation, and not collected for a long time.
Problem:
To me, a doctor is a very precious resource; other EmergencyPatient need doctors. However, to Java, the EmergencyPatient object is just a few bytes of memory.
Question:
What is the right way to solve this problem? (There are some resources that I want to be freed as soon as I know they’re no longer being used).
Thanks!
If you examine the 4 reference objects, there is one that will notify you when your object becomes “Eligible for garbage collection”. This means that you don’t have to wait for a “Big” GC, it can let you know during one of the minor passes if your object has become unreachable, even if it’s in one of the older generation areas.
I believe this is supposed to be the correct way to do what you are attempting.