On 10 July 2012 15:33, mschwartz <[email protected]> wrote: > JavaScript doesn't have a concept of destructors like many OO languages, >
I think "most OO languages" is an exaggeration. Rather, it is an artifact of the few (though popular) OO-languages with manual memory management. > but in a server-side context, there's a real need for them. Garbage > collection in JavaScript is done behind the scenes on objects that are no > longer referenced. When would you call an object's destructor: 1) when it > is no longer referenced, or 2) when it is garbage collected? > In practice, there is no difference between (1) and (2), because you cannot generally find out that something is no longer referenced except by doing (most of the work of) a garbage collection. At least not in a language with first-class functions and objects. > I suggest that if we could have some "destructor" support in v8, that it > be the former (no longer referenced). It is critical in server-side > environments that any (external) resources can be freed as soon as > possible. For example, there are a limited number of file descriptors > (fds) available to a Unix/Linux system, and if they're all tied up (open) > in some JS object that's been dereferenced, the server can run out of them. > If you deal with fds in wrapped C++ classes made as weak references, those > fds can be tied up for a long long time, until v8 maybe decides to GC and > call the weak callback. But if there were a mechanism to register a > callback to be called when an object is no longer referenced, the fds could > be closed and released to the OS/application for reuse long before V8 maybe > decides to garbage collect. > You are talking about finalization. It is folklore that using finalization for managing resources other than memory (especially limited resources like OS handles) is almost always a bad idea, because garbage collection is far too non-deterministic for that. You will have no guarantee that finalizers are invoked in a timely manner, because the GC cannot tell. I note that JavaScript 1.8.5 provides this: > > https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty > Maybe I misunderstand, but Object.defineProperty is perfectly standard ES5 functionality, and fully supported by V8. Where do you see the connection to finalization? /Andreas -- v8-users mailing list [email protected] http://groups.google.com/group/v8-users
