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.

  1. 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.

  2. What does ets:new(Name, [named_table]) answer?

    Answer

    The atom Name

    With named_table the name is registered and the call answers that atom.

  3. What does ets:lookup/2 always answer?

    Answer

    A list of rows

    The answer is a list because a bag can hold several rows for one key.

  4. 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.

  5. What does a bag keep?

    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.

  6. 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.

  7. What is the difference between set and ordered_set?

    Answer

    ordered_set keeps the rows sorted by key

    An ordered_set is a balanced tree keyed by term order, so its traversals come out sorted.

  8. What does a match spec contain?

    Answer

    A template, guard tests and result expressions

    The template with $1, $2 binds the tuple parts, the guards filter, and the result list builds the answer.

  9. Where does ets:select/2 run the match?

    Answer

    Inside the table

    The table does the matching, so only the selected results are copied to the caller.

  10. Which flag lets any process write to the table?

    Answer

    public

    public allows reads and writes from every process; protected allows 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

Banner image