ETS tables
Create a table
An ETS table is shared memory inside the VM: any process can read and write it without a message travelling through a mailbox. ets:new makes one, and the process that created it owns it: when that process dies, the table goes with it. The named_table flag registers the name, so other processes reach the table by atom instead of by id. Save this module as cache.erl.
-module(cache).
-export([start/0, put/2, get/1, size/0, remove/1]).
-define(TABLE, cache).
start() ->
ets:new(?TABLE, [named_table, set, public]),
ok.
put(Key, Value) ->
ets:insert(?TABLE, {Key, Value}).
get(Key) ->
case ets:lookup(?TABLE, Key) of
[{Key, Value}] ->
Value;
[] ->
undefined
end.
size() ->
ets:info(?TABLE, size).
remove(Key) ->
ets:delete(?TABLE, Key).
The public flag lets any process write; protected tables let everyone read and only the owner write, and private tables belong to the owner alone. lookup always answers a list, because in a bag several rows can share one key.
erlc cache.erl
erl
1> cache:start().
ok
2> cache:put(k, 1).
true
3> cache:get(k).
1
4> cache:get(missing).
undefined
5> cache:size().
1
6> ets:tab2list(cache).
[{k,1}]
7> cache:remove(k), ets:info(cache, size).
0
set and bag
The table 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, and a duplicate_bag keeps them all. Every table stores tuples, and the first element of the tuple is the key.
erl
1> ets:new(tags, [bag, named_table]).
tags
2> ets:insert(tags, {color, red}), ets:insert(tags, {color, blue}), ok.
ok
3> lists:sort(ets:lookup(tags, color)).
[{color,blue},{color,red}]
The sort in the third call is not decoration: the rows of a bag come back in no promised order, so a test that compares them compares a sorted list.
Ordered set
An ordered_set keeps the rows sorted by key, which makes tab2list and select answer in key order and makes lookups of neighbours cheap. The cost is a slower insert, because the table keeps a balanced tree instead of a hash.
erl
1> ets:new(ranked, [ordered_set, named_table]), ok.
ok
2> [ets:insert(ranked, {N, N * N}) || N <- [3, 1, 2]], ok.
ok
3> ets:tab2list(ranked).
[{1,1},{2,4},{3,9}]
Match specs
ets:select answers the rows that match a pattern. The pattern is a match spec: a template with variables such as '$1', a list of guard tests, and a list of expressions that build the answer. It runs inside the table, so only the results travel back to your process.
erl
1> ets:new(ranked, [ordered_set, named_table]), ok.
ok
2> [ets:insert(ranked, {N, N * N}) || N <- [3, 1, 2]], ok.
ok
3> ets:select(ranked, [{{'$1', '$2'}, [{'>', '$2', 2}], ['$1']}]).
[2,3]
4> ets:delete_all_objects(ranked), ets:info(ranked, size).
0
The same table with write_concurrency turns its internal locks finer and pays for it with slower reads; reach for it when several processes write the same table all day. For a cache of a few thousand rows the plain set is faster in both directions.
Next: Timers and timeouts
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 dies.
-
What does
ets:new(Name, [named_table])answer?Answer
The atom
NameWith
named_tablethe name is registered and the call answers that atom. -
What does
ets:lookup/2always answer?Answer
A list of rows
The answer is a list because a bag can hold several rows for one key.
-
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.
-
Why does the bag example sort the lookup result?
Answer
The rows come back in no promised order
Row order in a bag is not promised, so tests and output sort the rows first.
-
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 does a match spec contain?
Answer
A template, guard tests and result expressions
The template with
$1,$2binds the tuple parts, the guards filter, and the result list builds the answer. -
Where does
ets:select/2run the match?Answer
Inside the table
The table does the matching, so only the selected results are copied to the caller.
-
Which flag lets any process write to the table?
Answer
publicpublicallows reads and writes from every process;protectedallows only the owner to write.
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