0

I would like to do something like this:

class MyWeakReference<T> extends WeakReference<T> {

  void onClear() { .. run my code .. }
}

But since GC doesn't call clear(), but sets the referent to null directly, it seems like there is no way to invoke such code.

Ford O.
  • 1,394
  • 8
  • 25
  • If you register it with a `reference queue` you could then set a timer and periodically check if it has been `enqueued()`. Then you could run your code. In fact, you could write you own listener and register it and have a background process monitor the status. – WJS Aug 29 '19 at 14:03
  • See [`java.lang.ref.ReferenceQueue`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/ref/ReferenceQueue.html) or [`java.lang.ref.Cleaner`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/ref/Cleaner.html) (Java 9+). – Slaw Aug 29 '19 at 14:12

0 Answers0