Search code examples
javascriptgarbage-collectionspidermonkey

SpiderMonkey GC notification and weak references


Is it possible to be notified when SpiderMonkey has collected (or about to collect) a particular "GC thing" ?

In V8 there are "weak handles" that have callbacks attached to them, these are supposed to be called when V8 GC decides that the handle'd object has become unreachable. Even if the callback does not get called (which is possible according to V8 docs), we can still check if the object pointed to by the handle is about to be collected using v8::Persistent<T>::IsNearDeath().

In SpiderMonkey, we have PersistentRooted, which is a strong reference. But we have not found any way to safely reference an object in a weak manner, so we can check at least for one (or more) of the following conditions:

  • the object has become unreachable;
  • the object has been collected;
  • the object is about to be collected;
  • the object has only one reference (which is the one our application holds)

Solution

  • But we have not found any way to safely reference an object in a weak manner, so we can check at least for one (or more) of the following conditions

    [...]

    • the object has been collected;

    This can be achieved with weak references

    You can simply check whether they return null if you want to probe them.

    • the object is about to be collected;

    At least from C code the JSClass finalizer should allow you to do that.