v8Weak Callbacks


Remarks

Weak callbacks are primarily used for cleaning up C++ objects embedded in the InternalField of a v8::Object created from a v8::ObjectTemplate. When the JavaScript object is garbage collected, often times the C++ object must be deleted as well. By setting a weak callback, you can get notification that a javascript object has been garbage collected and take appropriate action.

It is VERY important to remember that garbage collection is NOT deterministic. Your program may exit with objects with weak reference callbacks registered that are never called. These callbacks are important for a properly behaving long-running program, but should not be relied on for releasing critical-path resources in a consistent or prompt fashion.

In order for the garbage collector to know when it should run, you have to tell it about the amount of space your C++ objects are using via the v8::Isolate::AdjustAmountOfExternalAllocatedMemory call. The parameter to this call is the change in bytes, so when you allocate it, you'd often send in sizeof(T) and when you clean up in your weak reference callback, you'd send in -sizeof(T).