Immediate closing of iterators

Brendan Eich brendan at mozilla.org
Fri Dec 22 14:08:53 PST 2006


On Dec 22, 2006, at 9:05 AM, Chris Hansen wrote:

> I would argue that the same
> reasoning applies to generators: if you create them and want to make
> sure they're closed then you have to close them yourself.  I don't
> think people (except pythonians maybe) would consider that
> unreasonable.

This is the 64,000 eollar (or euro, stabler currency :-/) question.

> Since finalization is tied to the GC (which might be conservative) it
> cannot, by definition, be relied on to release resources in something
> that resembles a timely fashion, or at all.

If you can't rely on the GC to recover memory in the absence of  
client code bugs that generate uncollectible graphs, you need a new GC.

> I would claim that as soon as generators start to resemble threads or
> coroutines the situation changes.  In java, if a thread blocks
> indefinitely in a try clause then then the finally clause will never
> be executed (at least not as far as I can tell).

It's a good point, I say again I like it. Need to get feedback from  
others.

> There's another issue with finally guarantees that I don't think has
> been mentioned: which thread is it that closes the generators?
> Consider this example:
>
> let genCount = 0;
> function makeGenerator() {
>  genCount++;
>  return myGenerator();
> }
>
> function myGenerator() {
>  try {
>    yield 1;
>    yield 2;
>  } finally {
>    genCount--;
>  }
> }
>
> Imagine that the program has been running for a while and the GC
> decides to set in right after makeGenerator has read genCount but
> before it has incremented it.  If the GC happens to close some of
> these generators then genCount will be in an inconsistent state when
> execution continues.  If the GC doesn't then who does?

ECMA-262 does not define anything to-do with threads, and ES4 won't  
either.

In the browser, the execution model is run-to-completion.  No event  
handler, not even a timeout, may preempt a running script (even if  
the script is flying a modal dialog; contrary behavior including in  
Firefox is a bug).  The GC will not preempt makeGenerator at  
arbitrary points, either.  It might run synchronously (nesting on the  
current thread stack) at a backward branch or return (after the  
result has been evaluated), or from a native method, getter, or  
setter.  It won't run in the midst of genCount++.

Any multi-threaded browser has to preserve the invariants of this  
model, for backward compatibility and developer sanity.

The browser execution rules are not well-specified, but they should  
be, in a browser embedding spec (not directly in ES4).  Fodder for  
the WHATWG or W3C.

/be



More information about the Es4-discuss mailing list