Elixir ETS Concurrency
ETS concurrency options are settings that tune a table for many processes at once. They are given when the table is created.
Turn on read concurrency
Create a table with the read option set and check the setting.
table = :ets.new(:store, [:set, :public, read_concurrency: true])
IO.inspect(:ets.info(table, :read_concurrency))Turn on write concurrency
Create a table with the write option set and check the setting.
table = :ets.new(:store, [:set, :public, write_concurrency: true])
IO.inspect(:ets.info(table, :write_concurrency))Five readers see the same row
Start five tasks that each read the same row from a read-tuned table.
table = :ets.new(:store, [:set, :public, read_concurrency: true])
:ets.insert(table, {"greeting", "hello"})
tasks = Enum.map(1..5, fn _ -> Task.async(fn -> :ets.lookup(table, "greeting") |> hd() |> elem(1) end) end)
IO.inspect(Enum.map(tasks, &Task.await/1))Example
table = :ets.new(:store, [:set, :public, write_concurrency: true])
tasks = Enum.map(1..5, fn n -> Task.async(fn -> :ets.insert(table, {"key#{n}", n}) end) end)
Enum.each(tasks, &Task.await/1)
IO.inspect(:ets.info(table, :size))
IO.inspect(Enum.sort(:ets.tab2list(table)))Key points
- Read concurrency: Set the read_concurrency option to true to tune a table for many readers at once.
- Write concurrency: Set the write_concurrency option to true to tune a table for many writers at once.
- Both options: A table can set the read and write options at the same time.
- Shared reads: Concurrent readers each see the same stored row.
- Default behaviour: Without these options a table still works for ordinary use.
In this example, a write-tuned table is created. Five tasks each insert a different key, and every task is awaited before the checks run. The size is 5 and the sorted list shows all five rows, which proves every writer landed.
Note
These options help most when many processes use the same table at once.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which option tunes a table for many readers at once?