ETS in depth

The ETS lesson creates a table and reads it by key. A production table needs four more things: the record shape that decides which field is the key, an increment a hundred processes can do at once, a query that runs inside the table instead of copying every row out, and a plan for the moment the owner dies. Each one is an option or a call of the same ets module, and each one is a choice a cache, a registry or a counter has to make.

The options that matter

{keypos, N} moves the key off the first element, which lets a program keep its record order and key by a field in the middle. The protection of a table is protected unless the creator asks for public or private, so every other process may read and only the owner may write. The program also shows the three calls that a careful writer uses instead of a read followed by a write: an insert that refuses to replace, an update of one field, and a take that deletes and answers in one step:

options.erl

-module(options). -export([main/0]). main() -> Table = ets:new(people, [set, {keypos, 2}]), true = ets:insert(Table, [{ada, 36, london}, {grace, 45, new_york}]), io:format("keypos: ~p~n", [ets:info(Table, keypos)]), io:format("by age: ~p~n", [ets:lookup(Table, 45)]), io:format("insert_new: ~p~n", [ets:insert_new(Table, [{ada, 36, paris}])]), true = ets:update_element(Table, 36, {3, paris}), io:format("after the update: ~p~n", [ets:lookup(Table, 36)]), io:format("take: ~p~n", [ets:take(Table, 45)]), io:format("size: ~p~n", [ets:info(Table, size)]), io:format("protected: ~p~n", [ets:info(Table, protection)]).

erlc options.erl

erl -noshell -eval 'options:main(), halt().'

keypos: 2 by age: [{grace,45,new_york}] insert_new: false after the update: [{ada,36,paris}] take: [{grace,45,new_york}] size: 1 protected: protected

ets:insert_new/2 answered false because the key 36 was already there, which is the check a registry needs: two processes that try to register the same name cannot both see true. ets:update_element/3 changed the third field and left the key and the name alone, and ets:take/2 removed the row it answered, so the size fell to one. All three are single calls, which matters on a table several processes share: a read followed by a write leaves a window in which another process changes the row.

Atomic counters

ets:update_counter/3 adds to a field and answers the new value in one operation, without a read that another process can race. {write_concurrency, true} tells the table to split its write locks, so writers on different keys do not queue behind one another; the price is a slower single writer and a little more memory. The program lets four processes add a hundred each:

hits.erl

-module(hits). -export([main/0]). main() -> Table = ets:new(hits, [named_table, public, {write_concurrency, true}]), true = ets:insert(Table, {total, 0}), Self = self(), Pids = [spawn(fun() -> [ets:update_counter(Table, total, 1) || _ <- lists:seq(1, 100)], Self ! {done, self()} end) || _ <- lists:seq(1, 4)], [receive {done, Pid} -> ok end || Pid <- Pids], io:format("total: ~p~n", [ets:lookup_element(Table, total, 2)]), io:format("within the threshold: ~p~n", [ets:update_counter(Table, total, {2, 5, 410, 0})]), io:format("over the threshold: ~p~n", [ets:update_counter(Table, total, {2, 10, 410, 0})]), io:format("insert_new on the counter: ~p~n", [ets:insert_new(Table, {total, 0})]).

erlc hits.erl

erl -noshell -eval 'hits:main(), halt().'

total: 400 within the threshold: 405 over the threshold: 0 insert_new on the counter: false

The total is always 400, whatever order the four processes take, because each increment is atomic. The four element form of the increment is a counter with a ceiling: the third element is the limit and the fourth the value that replaces the counter when the increment would pass it. From 405 an increment of ten would pass 410, so the counter wraps to zero and the call answers zero, which is how a rate window resets without a separate read.

Match specs in depth

A match spec is a list of clauses, and the table uses the first whose pattern and guards match. Each clause is {Pattern, Guards, Body}, the guards test the variables the pattern bound, and the body builds the answer from them. A second clause is therefore an or over the same query, not a fallback: the program asks for the high scores and the low ones in one call, then for a range of keys:

matchspec.erl

-module(matchspec). -export([main/0]). main() -> Table = ets:new(scores, [ordered_set]), true = ets:insert(Table, [{ann, 15}, {bob, 25}, {cid, 35}, {dot, 45}]), High = [{{'$1', '$2'}, [{'>', '$2', 20}], ['$1']}], Edge = [{{'$1', '$2'}, [{'>=', '$1', bob}, {'=<', '$1', cid}], ['$1']}], Both = [{{'$1', '$2'}, [{'>', '$2', 30}], ['$1']}, {{'$1', '$2'}, [{'<', '$2', 20}], ['$1']}], io:format("high: ~p~n", [ets:select(Table, High)]), io:format("a key range: ~p~n", [ets:select(Table, Edge)]), io:format("two clauses: ~p~n", [ets:select(Table, Both)]), io:format("match_object: ~p~n", [ets:match_object(Table, {'_', 25})]), io:format("foldl: ~p~n", [ets:foldl(fun({_Name, Score}, Sum) -> Sum + Score end, 0, Table)]).

erlc matchspec.erl

erl -noshell -eval 'matchspec:main(), halt().'

high: [bob,cid,dot] a key range: [bob,cid] two clauses: [ann,cid,dot] match_object: [{bob,25}] foldl: 120

The key range works because an ordered_set compares keys by term order, so a guard on '$1' is a range scan over the tree. In a plain set the same spec still runs, but the table visits every row and the guard filters afterwards, which is the difference between a query and a scan. ets:match_object/2 is the shorthand for a spec whose body is the whole row and whose pattern is written with '_'. ets:foldl/3 visits every row in the calling process, so use it only when the answer needs work the match spec cannot express.

The heir of a table

A table dies with its owner unless an heir is named. The heir is a pid, and the table is transferred to it when the owner ends; the heir receives the 'ETS-TRANSFER' message with the table, the old owner and the term the option carried. The program makes the main process the heir and kills the owner:

heir.erl

-module(heir). -export([main/0]). main() -> Self = self(), Pid = spawn(fun() -> Table = ets:new(kept, [named_table, public, {heir, Self, gift}]), true = ets:insert(Table, {k, v}), Self ! {ready, Table}, receive stop -> ok end end), Table = receive {ready, T} -> T end, Pid ! stop, receive {'ETS-TRANSFER', Table, Pid, HeirData} -> io:format("inherited with: ~p~n", [HeirData]) after 1000 -> io:format("no transfer~n") end, io:format("rows: ~p~n", [ets:lookup(Table, k)]), io:format("owner is the main process: ~p~n", [ets:info(Table, owner) =:= self()]).

erlc heir.erl

erl -noshell -eval 'heir:main(), halt().'

inherited with: gift rows: [{k,v}] owner is the main process: true

The rows survived the owner because the table never became unowned. A heir is what a supervisor child uses to keep a cache alive across a restart of the process that filled it, and the term of the option is how the new owner learns what the table was for. The alternative is ets:give_away/3 from the lesson on the owner, which hands the table over while the owner is still alive.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the {keypos, N} option change?

    Answer

    The position of the field that is the key

    The key is the first element by default, and keypos names another position.

  2. What does ets:insert_new/2 answer when the key is already in the table?

    Answer

    false

    The call refuses to replace a row and reports the refusal as false.

  3. What does ets:update_counter(T, K, {2, 5, 410, 0}) do?

    Answer

    Adds five until the field passes 410, then sets it to 0

    The third element is a ceiling and the fourth the value used when the increment would pass it.

  4. What does {write_concurrency, true} trade away?

    Answer

    Memory and single-writer speed for parallel writers

    Finer locks let writers on different keys run together, at the cost of memory and a slower lone writer.

  5. How does ets:select/2 treat a list of several clauses?

    Answer

    It uses the first that matches for each row

    Each row is tested against the clauses in order and the first match decides the answer.

  6. What does a heir receive when the owner of the table ends?

    Answer

    An 'ETS-TRANSFER' message with the table

    The table is transferred, and the heir gets the table id, the old owner and the term of the option.

  7. What does this module print? -module(q1). -export([main/0]). main() -> T = ets:new(t, [set, {keypos, 2}]), true = ets:insert(T, [{a, 1}, {b, 2}]), io:format("~p~n", [ets:lookup(T, 2)]).

    Answer

    [{b,2}]

    With keypos two the second element is the key, and 2 names the row {b,2}.

  8. What does this module print? -module(q2). -export([main/0]). main() -> T = ets:new(t, [set]), true = ets:insert(T, {k, 1}), io:format("~p~n", [ets:update_counter(T, k, 4)]), io:format("~p~n", [ets:lookup_element(T, k, 2)]).

    Answer

    5 / 5

    The increment adds four to one, answers the new value, and the row now holds it.

  9. What does this module print? -module(q3). -export([main/0]). main() -> T = ets:new(t, [ordered_set]), true = ets:insert(T, [{a, 1}, {b, 2}, {c, 3}]), S = [{{'$1', '$2'}, [{'>=', '$1', b}], ['$1']}], io:format("~p~n", [ets:select(T, S)]).

    Answer

    [b,c]

    The guard compares the key with the atom b in term order, so the keys from b up match.

  10. What does this module print? -module(q4). -export([main/0]). main() -> Self = self(), Pid = spawn(fun() -> T = ets:new(t, [named_table, public, {heir, Self, gift}]), true = ets:insert(T, {k, v}), Self ! ready, receive stop -> ok end end), receive ready -> ok end, Pid ! stop, receive {'ETS-TRANSFER', T, Pid, Term} -> io:format("~p ~p~n", [Term, ets:info(T, size)]) after 1000 -> io:format("no transfer~n") end.

    Answer

    gift 1

    The table is transferred with the term of the option and keeps its one row.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev

Изображение баннера