ETS tables
An ETS table is shared memory inside the Erlang VM: every process reads and writes it directly, without a message travelling through a mailbox. It is the data structure behind a cache, a registry and the state that must outlive the process which built it, and it is the one mutable thing the language gives a process without a protocol. The trade is that a table lives in one process's name: the process that created it owns it, and the table disappears with the owner unless the table was handed over. The ETS in depth lesson takes the options and the match specs further; this one covers the table a program actually needs.
Create a table
ets:new/2 makes a table and answers its name or its identifier. With the named_table flag the name is registered, so any process reaches the table by atom; without it the caller keeps the identifier it got back. The public flag lets every process write, which is what the program uses to read the table through the bare name:
cache.erl
-module(cache). -export([main/0]). main() -> Table = ets:new(cache, [named_table, set, public]), io:format("the name: ~p~n", [Table]), true = ets:insert(Table, {k, 1}), io:format("lookup: ~p~n", [ets:lookup(Table, k)]), io:format("missing: ~p~n", [ets:lookup(Table, missing)]), io:format("by name: ~p~n", [ets:lookup(cache, k)]), io:format("size: ~p~n", [ets:info(Table, size)]), io:format("all: ~p~n", [ets:tab2list(Table)]), true = ets:delete(Table, k), io:format("after delete: ~p~n", [ets:info(Table, size)]).
erlc cache.erl
erl -noshell -eval 'cache:main(), halt().'
the name: cache lookup: [{k,1}] missing: [] by name: [{k,1}] size: 1 all: [{k,1}] after delete: 0
ets:lookup/2 answers a list even for a set, because a bag can hold several rows for one key, and a miss is the empty list, not undefined. ets:insert/2 answers true, which is why the program can assert it. An unnamed table is reached only through the identifier, and the identifier stays valid until the table is deleted or its owner dies.
set, bag and duplicate_bag
The type decides what a duplicate key means. A set keeps one row per key, so a second insert with the same key replaces the first. A bag keeps one row per key and value and drops an exact duplicate, while a duplicate_bag keeps every row it is given. All three store tuples whose first element is the key:
types.erl
-module(types). -export([main/0]). main() -> Set = ets:new(seen, [set]), true = ets:insert(Set, {color, red}), true = ets:insert(Set, {color, blue}), true = ets:insert(Set, {color, red}), Bag = ets:new(tags, [bag]), true = ets:insert(Bag, {color, red}), true = ets:insert(Bag, {color, blue}), true = ets:insert(Bag, {color, red}), Many = ets:new(log, [duplicate_bag]), true = ets:insert(Many, {tick, 1}), true = ets:insert(Many, {tick, 1}), io:format("set: ~p~n", [ets:lookup(Set, color)]), io:format("bag: ~p~n", [lists:sort(ets:lookup(Bag, color))]), io:format("duplicate_bag: ~p~n", [ets:lookup(Many, tick)]), io:format("one key, two rows: ~p~n", [ets:info(Bag, size)]).
erlc types.erl
erl -noshell -eval 'types:main(), halt().'
set: [{color,red}] bag: [{color,blue},{color,red}] duplicate_bag: [{tick,1},{tick,1}] one key, two rows: 2
The lists:sort/1 in the bag line is not decoration: the rows of a bag come back in no promised order, so a test that compares them compares a sorted list. A set answers its one row directly, and the third insert of the same pair into the bag changed nothing because the pair was already there.
Ordered set
An ordered_set keeps the rows sorted by key, which makes tab2list/1 and select/2 answer in key order and makes a lookup of a neighbour cheap: ets:next/2 and ets:prev/2 walk the table one key at a time. The cost is a slower insert, because the table keeps a balanced tree instead of a hash:
ranked.erl
-module(ranked). -export([main/0]). main() -> Table = ets:new(ranked, [ordered_set]), true = ets:insert(Table, [{3, 9}, {1, 1}, {2, 4}]), io:format("rows: ~p~n", [ets:tab2list(Table)]), io:format("first: ~p~n", [ets:first(Table)]), io:format("next of 2: ~p~n", [ets:next(Table, 2)]), io:format("last: ~p~n", [ets:last(Table)]), io:format("prev of 2: ~p~n", [ets:prev(Table, 2)]), io:format("lookup: ~p~n", [ets:lookup(Table, 2)]).
erlc ranked.erl
erl -noshell -eval 'ranked:main(), halt().'
rows: [{1,1},{2,4},{3,9}] first: 1 next of 2: 3 last: 3 prev of 2: 1 lookup: [{2,4}]
The rows went in out of order and came back sorted. ets:next/2 answers '$end_of_table' past the last key and ets:prev(Table, First) answers '$end_of_table' before the first, which is how a walk over the table stops. A set has no such order, so next/2 works only on an ordered_set.
Match specs
ets:select/2 answers the rows that match a pattern, and the pattern is a match spec: a template with the variables '$1' and '$2', a list of guard tests, and a list of expressions that build the answer. It runs inside the table, so only the chosen values travel back to the caller. The program uses one spec for the rows and a second one to count and delete them, and shows the trap of the count:
spec.erl
-module(spec). -export([main/0]). main() -> Table = ets:new(ranked, [ordered_set]), true = ets:insert(Table, [{1, 10}, {2, 20}, {3, 30}, {4, 40}]), Rows = [{{'$1', '$2'}, [{'>', '$2', 15}], ['$1']}], Count = [{{'$1', '$2'}, [{'>', '$2', 15}], [true]}], io:format("select: ~p~n", [ets:select(Table, Rows)]), io:format("count with [true]: ~p~n", [ets:select_count(Table, Count)]), io:format("count with ['$1']: ~p~n", [ets:select_count(Table, Rows)]), io:format("deleted rows: ~p~n", [ets:select_delete(Table, Count)]), io:format("left: ~p~n", [ets:tab2list(Table)]).
erlc spec.erl
erl -noshell -eval 'spec:main(), halt().'
select: [2,3,4] count with [true]: 3 count with ['$1']: 0 deleted rows: 3 left: [{1,10}]
ets:select/2 returns the body of the spec for each match, so ['$1'] gives the keys. The two counting calls use the same guard and the same template, and only the body differs: ets:select_count/2 and ets:select_delete/2 count a match only when the body answers true, so a body of ['$1'] counts zero and deletes nothing. A spec written for select and pasted into select_count is the mistake, and it fails without an error message.
The owner of the table
The process that called ets:new/2 owns the table, and the table is deleted when that process ends. That is a feature: a cache built by a worker goes away with the worker instead of leaking. It is also the mistake a reader makes when a table disappears: the process that created it was a short lived one. ets:give_away/3 hands the table to another process before the owner ends:
owner.erl
-module(owner). -export([main/0]). main() -> {Gone, Pid} = spawn_owner(owned), io:format("while the owner lives: ~p~n", [ets:lookup(Gone, k)]), Pid ! stop, ok = wait_down(Pid), io:format("after the owner died: ~p~n", [ets:info(Gone)]), {Kept, Pid2} = spawn_owner(kept), Pid2 ! {give_away, self()}, ok = wait_down(Pid2), io:format("after the handover: ~p~n", [ets:lookup(Kept, k)]). spawn_owner(Name) -> Parent = self(), Pid = spawn(fun() -> Table = ets:new(Name, [named_table, public]), true = ets:insert(Table, {k, v}), Parent ! {ready, Table, self()}, receive {give_away, NewOwner} -> true = ets:give_away(Table, NewOwner, gift); stop -> ok end end), receive {ready, Table, Pid} -> {Table, Pid} end. wait_down(Pid) -> Ref = monitor(process, Pid), receive {'DOWN', Ref, process, Pid, _Reason} -> ok end.
erlc owner.erl
erl -noshell -eval 'owner:main(), halt().'
while the owner lives: [{k,v}] after the owner died: undefined after the handover: [{k,v}]
ets:info(Table) answers undefined for a table that no longer exists, so a reader can check the owner instead of guessing. When the owner of a long lived table is the process that started the system, the table outlives every call, and a heir option can name a process that inherits it if the owner crashes. Three rules keep a table healthy: one process owns it, the owner is supervised or is the system itself, and a worker that builds a cache hands it over before it ends.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which process owns an ETS table?
Answer
The process that created it
The creator owns the table, and the table is deleted when that process ends.
-
What does
ets:lookup/2answer for a key that is not in the table?Answer
[]The answer is always a list of rows, and a miss is the empty list.
-
What happens on a second insert with the same key in a
set?Answer
The old row is replaced
A set holds one row per key, so the newer tuple wins.
-
What does a
bagkeep?Answer
Several rows per key, but no exact duplicates
A bag allows several values per key and drops an insert that repeats a row exactly.
-
What is the difference between
setandordered_set?Answer
ordered_setkeeps the rows sorted by keyAn ordered_set is a balanced tree keyed by term order, so its traversals come out sorted.
-
What must the body of a match spec answer for
ets:select_count/2to count a match?Answer
trueThe counting calls count only the matches whose body answers
true, so a body of['$1']counts zero. -
What does this module print?
-module(q1). -export([main/0]). main() -> T = ets:new(t, [set]), true = ets:insert(T, {a, 1}), io:format("~p~n", [length(ets:lookup(T, b))]).Answer
0A lookup answers a list of rows, and a missing key contributes none, so the list is empty and its length is zero.
-
What does this module print?
-module(q2). -export([main/0]). main() -> T = ets:new(t, [bag]), true = ets:insert(T, {k, 1}), true = ets:insert(T, {k, 1}), true = ets:insert(T, {k, 2}), io:format("~p~n", [lists:sort(ets:lookup(T, k))]).Answer
[{k,1},{k,2}]A bag keeps one row per key and value, so the repeated
{k,1}is dropped and the sort puts the rows in order. -
What does this module print?
-module(q3). -export([main/0]). main() -> T = ets:new(t, [ordered_set]), true = ets:insert(T, [{2, b}, {1, a}, {3, c}]), io:format("~p~n", [ets:next(T, 2)]).Answer
3ets:next/2answers the key after the given one in key order, and3follows2. -
What does this module print?
-module(q4). -export([main/0]). main() -> Self = self(), Pid = spawn(fun() -> T = ets:new(t, [named_table, public]), true = ets:insert(T, {k, 1}), Self ! ready, receive stop -> ok end end), receive ready -> ok end, Pid ! stop, wait(Pid), io:format("~p~n", [ets:info(t)]). wait(Pid) -> Ref = monitor(process, Pid), receive {'DOWN', Ref, process, Pid, _} -> ok end.Answer
undefinedThe spawned process created the table, so the table is deleted when that process ends and
ets:info/1answersundefined.
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.
Article author: Arthur Isaev