Callback when variable is no longer valid

23 views
Skip to first unread message

Gautham B A

unread,
May 20, 2019, 12:59:18 AM5/20/19
to v8-users
Hi all,

I'm trying to track when a variable becomes invalid.
Consider the following code where the variable goes out of scope -

function SomeFunction() {
for(let i = 0; i < 10; ++i) {
let instance = new MyClass(); // MyClass is implemented in C++
}
// instance goes out of scope and isn't accessible at this line
}

Or when a variable gets reassigned.

function SomeFunction() {
let instance = new MyClass(); // MyClass is implemented in C++
instance = 10; // instance gets reassigned
}

Does v8 provide any callbacks that I can register on the object returned by MyClass which gets called in the above two scenarios?

The motivation behind my ask is that, When an instance of MyClass is created, some system resources (such as database connections etc) are allocated and bound to the instance. I wish to claim them back as soon as we can detect that the variable's value is unusable, as described in the above two scenarios.

Thanks,
--Gautham

Ben Noordhuis

unread,
May 20, 2019, 4:07:11 AM5/20/19
to v8-users
If you wrap the object in a v8::Persistent<v8::Object> and then call
persistent_handle.SetWeak(...), the garbage collector will invoke your
callback when the object is reclaimed.

That isn't exactly what you're asking for but it's the closest thing.
What you want doesn't exist and cannot exist because it would be
prohibitively expensive. Static escape analysis is easily defeated in
JS. You effectively would have to perform a full GC after every
statement.
Reply all
Reply to author
Forward
0 new messages