[erlang-questions] Design question -- a valid or foolhardy approach to ets update?

Sverker Eriksson <>
Tue Jul 14 17:00:13 CEST 2009


Ulf Wiger wrote:
> Note also that update_counter() requires the key to already
> exist in the table. Try to find a good place to initially
> create the counter. Otherwise, a fairly common pattern is:
>
> update_counter(Key, Incr) ->
>    try ets:update_counter(?tab, Key, {#counter.value, Incr})
>    catch
>       error:_ -> init_counter(Key, Incr)
>    end.
>
> init_counter(Key, Incr) ->
>    true = ets:insert_new(?tab, #counter{key = Key, value = Incr}),
>    Incr.
>
> ...but this obviously messes with atomicity.
>
I think you will be "safe" as long as you catch the unlikely race when 
insert_new fails:

init_counter(Key, Incr) ->
    case ets:insert_new(?tab, #counter{key = Key, value = Incr}) of
        true -> Incr;
        false -> update_counter(Key, Incr)
    end.


/Sverker, Erlang/OTP



More information about the erlang-questions mailing list