Yikes! It’s been longer than I thought it’s been since I last wrote on JsRT. Sorry about that, we’ve been a little busy.
With the two major concepts, runtimes and contexts, covered, there were a few additional things that need to be addressed for hosts that want to use JsRT. Probably the most important is how memory management is coordinated between Chakra and the host.
As you know, JavaScript is a garbage collected language, and everything you allocate through the JsRT API (with the exception of runtimes) is managed by the Chakra garbage collector. References will continue to live only as long as the garbage collector thinks they are “alive.” Once the GC thinks a reference is dead, the next collection will free up the memory and the reference will become invalid. The garbage collector looks in two places when determining if a reference is alive:
- The runtime’s garbage collected heap.
- The stack of the runtime’s current thread.
So a reference to a JavaScript value that is stored inside of another JavaScript value or in a local variable on the stack will always be seen by the garbage collector. But if a host stores a reference somewhere where the GC isn’t going to look (for example, in a host-allocated heap), then the reference will not be seen by the garbage collector and may result in premature collection of values that are still in use by the host. (When relying on a stack reference to keep a reference alive, you have to be extra careful–some language compilers (such as VC++) will optimize away stack variables where possible.)
If a host is going to store a reference where the GC can’t see it, it will need to manually add a reference to the object itself by calling JsAddRef
. This will ensure the object will not go away until JsRelease
is called. Calls to JsAddRef
/JsRelease
have to be paired–unbalanced calls will result in objects being collected too soon or staying alive forever.
You should also follow me on Twitter here.