Soon after starting with Google’s v8 JavaScript engine you will probably start using Persistent<>::MakeWeak(). MakeWeak() allows you to specify a callback that is called when the referenced object is about to be deleted by the garbage collection. This could be quite handy particularly when you want to keep the lifetime of your C++ object in sync with its JavaScript counterpart.
Unfortunately, v8 does not guarantee that your callback is called when the context is disposed, or even when the program terminates. v8′s garbage collection is very lazy and is only done when really needed, i.e. when you’re running out of memory. And this might be never, leaving you callbacks uncalled at the end of the program. This could be bad if you clean up more than just memory in your MakeWeak() callback.
Forcing the garbage collection would certainly solve the problem, but v8 doesn’t expose much of the GC’s interface to the developer and this particular functionality is missing. There is an (optional) extension that allows to perform garbage collection from within JavaScript – which doesn’t help in all cases, e.g. after context disposal.
After playing around with this for a while, and reading some of the discussions on the web, I was surprised that there seems to be a very simple solution to the problem:
while(!V8::IdleNotification()) {};
Just for your information, here is the description of the function:
Optional notification that the embedder is idle. V8 uses the notification to reduce memory footprint. This call can be used repeatedly if the embedder remains idle. Returns true if the embedder should stop calling IdleNotification until real work has been done. This indicates that V8 has done as much cleanup as it will be able to do.
No word about garbage collection.
[...] Jansen’s post about using V8::IdleNotification() to invoke the garbage [...]
[...] referenced in Thomas Jansen’s blog post Force Garbage Collection, he notes that disposing of a V8 Context does not necessarily invoke the garbage [...]