How to prevent an object from getting garbage collected?
Are there any approaches by finalize or phantom reference or any other approaches?
I was asked this
I wonder if what they're going for is the pattern with resource pools (e.g. for network/db connections, or threads) where you use finalize to return a resource to the pool so that the actual object holding the resource isn't GC'ed.
Stupid example, in Java-like pseudocode and missing any kind of synchronization:
class SlowResourceInternal {
private final SlowResourcePool parent;
returnToPool() {
parent.add(this);
}
}
class SlowResourceHolder {
private final SlowResourceInternal impl;
finalize() {
if (impl != null) impl.returnToPool();
}
}