4 ms·
>finalized while you're still "using" them. It's a well known way to deal with such cases by using an additional weak reference. (even I think J. Bloch has men
by xxs 2y ago
>finalized while you're still "using" them.
It's a well known way to deal with such cases by using an additional weak reference. (even I think J. Bloch has mentioned it). Here (typing w/o an other editor, excuse typos):
class X<T> extends PhantomRefenece<T> {
final WeakReference<T> weak;
X(T ref, ReferenceQueue<? super T> q){
super(ref, q);
this.weak = new WeakReference<>(ref);
}
}
...
for (X x; (x = (X)q.poll()) != null;) {
process(x.weak.get());
}
This is why a mentioned it is effectively pre-mortrem. PhantomReference still keeps the referent, it's just not possible to retrieve it as get() is overridden.
- immibis 2y agoBad idea. Weak reference can be removed at the same time. You're supposed to let the PhantomReference contain the underlying thing that you want to delete when the object is GCed, such as a native handle.