DynamicSupervisor starts and supervises child processes on demand when the required number of workers is unknown in advance. Unlike Supervisor, it starts without a predefined child list and accepts children through DynamicSupervisor.start_child/2. section 9.2.2
Use it to:
- Register the supervisor locally so application code can request new supervised workers by name. section 9.2.2
- Treat {:error, {:already_started, pid}} as success when a named worker already exists. section 9.2.3
- Rely on serialized child-start requests to avoid races between concurrent callers, while recognizing the synchronous call cost. section 9.2.3
On-demand to-do servers
Todo.Cache runs as a named DynamicSupervisor. Its server_process/1 function starts a Todo.Server for a list and returns either the new PID or the PID of an already-registered server. section 9.2.2 section 9.2.3
Listing 9.11 Finding a to-do server (dynamic_workers/lib/todo/cache.ex)
defmodule Todo.Cache do
...
def server_process(todo_list_name) do
case start_child(todo_list_name) do
{:ok, pid} -> pid #1
{:error, {:already_started, pid}} -> pid #2
end
end
defp start_child(todo_list_name) do
DynamicSupervisor.start_child(
__MODULE__,
{Todo.Server, todo_list_name}
)
end
end
Shows the concise lookup pattern that handles both newly started and already running workers. section 9.2.3
