[erlang-questions] dialyzer: possible race condition with insert after lookup

Ulf Wiger <>
Sun Oct 23 21:28:02 CEST 2011


No, you'll want to stick to the update_counter semantics: the point of using ets:insert_new() and then update_counter() again, was that even if another process does the same thing in parallel, only one will get to insert the zero value; then both will use update_counter(), which will be atomic and thread-safe.

BR,
Ulf

On 23 Oct 2011, at 21:19, Joel Reymont wrote:

> What about this?
> 
>            _ = case ets:lookup(stats, Key1) of
>                    [{Key1, TS, latency, OldDelta}] ->
>                        %% have timings, average
>                        ets:insert(stats, [{Key1, TS, latency, (OldDelta + Delta) / 2}]);
>                    _ ->
>                        %% first timing, store
>                        ets:insert(stats, [{Key1, now(), latency, Delta}])
>                end;
> 
> On Oct 23, 2011, at 8:00 PM, Ulf Wiger wrote:
> 
>> 
>> This might please Dialyzer (I haven't tried):
>> 
>> bump(Key, Value) ->
>>  try ets:update_counter(stats, Key, {4, Value})
>>  catch
>>     error:_ ->
>>        ets:insert_new(stats, {Key, now(), count, 0}),
>>        ets:update_counter(stats, Key, {4, Value})
>>  end.
> 
> --------------------------------------------------------------------------
> - for hire: mac osx device driver ninja, kernel extensions and usb drivers
> ---------------------+------------+---------------------------------------
> http://wagerlabs.com | @wagerlabs | http://www.linkedin.com/in/joelreymont
> ---------------------+------------+---------------------------------------
> 

Ulf Wiger, CTO, Erlang Solutions, Ltd.
http://erlang-solutions.com






More information about the erlang-questions mailing list