lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 20 January 2015 at 00:34, Andrew Starks <andrew.starks@trms.com> wrote:
> On Monday, January 19, 2015, William Ahern <william@25thandclement.com>
> wrote:
>> Maybe you already do this, but in Lua 5.2 and 5.3 you can catch the leak
>> by
>> using the object to index a weak table, where you store a table with a
>> __gc
>> metamethod hook to trigger your cleanup logic. (In Lua 5.1 you can use the
>> undocumented newproxy in lieu of table __gc metamethods.)
>>
>> I use this as a fail-safe in several of my applications. It's basically
>> operates as a destructor that you can attach to objects without having to
>> hack their implementation (e.g. attach a __gc handler to the object
>> itself).
>>
>> Because you never know when the GC will run, I usually have a task with
>> runs
>> every N seconds to step through the GC. That way leaked object recyling
>> will
>> happen within bounded wallclock time, rather than based on memory
>> pressure.
>> This helps to reduce GC jitter, anyhow.
>>
>
> Wow. This is a great idea, if I'm following it.
>
> Do I have this correct: when you are doing something that may need to be
> rolled back, you attach the roll back to a table with weak keys. If failure
> happens,  the key is collected because the other references die with the
> failure. This releases the value associated with the key, which is a table
> that has a __gc method; the cleanup function.
>
> You could wrap pcall to take the clean up function as an argument and it
> would create the fail safe and also dissarm it, should the call succeed.
>
> Is that along the lines of what you were saying?

You can see it in action here:
https://github.com/daurnimator/cqueues/blob/7c4053b23be9be7df1a5827adcc1194aa08f3f58/src/dns.resolvers.lua#L21
(Code originally William Ahern's, I just forked to add Lua 5.1 support
via newproxy)