GenServer
A GenServer in Elixir is the receive loop of the state lesson with the loop, the naming and the error handling written for you. A module declares the callbacks, use GenServer provides the rest, and the runtime calls init/1 once and then one callback per message. The result is the server shape of OTP: a process with a state, a public API and a place for every message.
A counter as a GenServer
The module below keeps one integer. increment/0 is a cast because nobody waits for the answer, and add/1 and value/0 are calls because the caller needs the number:
counter.exs
defmodule Counter do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__) def increment, do: GenServer.cast(__MODULE__, :increment) def add(n), do: GenServer.call(__MODULE__, {:add, n}) def value, do: GenServer.call(__MODULE__, :value) @impl true def init(count), do: {:ok, count} @impl true def handle_cast(:increment, count), do: {:noreply, count + 1} @impl true def handle_call({:add, n}, _from, count), do: {:reply, count + n, count + n} def handle_call(:value, _from, count), do: {:reply, count, count} end {:ok, _pid} = Counter.start_link([]) Counter.increment() Counter.increment() IO.inspect(Counter.add(5)) IO.inspect(Counter.value())
elixir counter.exs
7
7
The two casts arrive before the call, and the mailbox keeps their order, so the counter is 2 before the addition. The public functions hide the messages: a caller writes Counter.add(5) and never builds the tuple, which is the part a hand-written loop leaves to every caller.
init, handle_call and handle_cast
Three callbacks carry almost every server. The return value of each one is a contract, and the compiler checks it with the behaviour of GenServer:
- init/1 receives the argument of start_link/1 and answers {:ok, state}.
- handle_call/3 receives the request, the caller and the state, and answers {:reply, answer, new_state}.
- handle_cast/2 receives the message and the state, and answers {:noreply, new_state}: a cast has no answer to send.
@impl true marks each callback, and the compiler warns when a function does not match the behaviour it claims to implement. The behaviours lesson shows that warning.
The name of the server
start_link/1 registers the process under a name, so the API functions do not need a pid. The name is an atom, and the runtime keeps the map from the atom to the pid:
named.exs
defmodule Named do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, 7, name: __MODULE__) def value, do: GenServer.call(__MODULE__, :value) @impl true def init(n), do: {:ok, n} @impl true def handle_call(:value, _from, n), do: {:reply, n, n} end {:ok, _pid} = Named.start_link([]) IO.inspect(is_pid(GenServer.whereis(Named))) IO.inspect(Named.value())
elixir named.exs
true
7
GenServer.whereis/1 answers the pid or nil; the pid itself changes on every run, so the program prints the check rather than the value. A second call to start_link/1 with the same name answers {:error, {:already_started, pid}}, which is how a program detects a server that is already running.
Work that does not block init
init/1 runs before the server answers anything, and a long job there delays every caller and the supervisor that started it. handle_continue/2 runs after init returns and keeps the startup short:
loader.exs
defmodule Loader do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, [], name: __MODULE__) def items, do: GenServer.call(__MODULE__, :items) @impl true def init(_opts), do: {:ok, [], {:continue, :load}} @impl true def handle_continue(:load, items), do: {:noreply, [:a, :b | items]} @impl true def handle_call(:items, _from, items), do: {:reply, items, items} end {:ok, _pid} = Loader.start_link([]) IO.inspect(Loader.items())
elixir loader.exs
[:a, :b]
The tuple {:ok, state, {:continue, message}} makes the runtime call handle_continue/2 before any other message, so the state is complete by the time the first call arrives. A supervisor starts the child faster, and a failed load crashes the server in the same place a failed init would.
A server that stops
A call can stop its server and still answer the caller. The tuple {:stop, reason, answer, state} sends the answer, then ends the process with the reason:
stop.exs
defmodule Stopper do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, :ready, name: __MODULE__) def stop, do: GenServer.call(__MODULE__, :stop) @impl true def init(state), do: {:ok, state} @impl true def handle_call(:stop, _from, state), do: {:stop, :normal, :bye, state} end {:ok, pid} = Stopper.start_link([]) IO.inspect(Stopper.stop()) Process.sleep(20) IO.inspect(Process.alive?(pid))
elixir stop.exs
:bye
false
The reason :normal tells a supervisor that the stop was intended, so a child with the default restart setting is not started again. The short sleep gives the process time to finish before the check, which a real program never needs because the supervisor receives the exit signal.
The mistake: a cast has no answer
GenServer.cast/2 answers :ok as soon as the message is in the mailbox, not the new state. A caller that treats the answer as the result reads the atom and thinks the server ignored the message:
mistake.exs
defmodule C do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__) def increment, do: GenServer.cast(__MODULE__, :increment) def value, do: GenServer.call(__MODULE__, :value) @impl true def init(count), do: {:ok, count} @impl true def handle_cast(:increment, count), do: {:noreply, count + 1} @impl true def handle_call(:value, _from, count), do: {:reply, count, count} end {:ok, _pid} = C.start_link([]) result = C.increment() IO.inspect(result) IO.inspect(C.value())
elixir mistake.exs
:ok
1
The increment happened, and the next call reads it. Use a call when the caller needs the answer, and a cast when the work can wait. The last lesson of this chapter, a GenServer is one process, shows what a call costs when every caller waits for the same server.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
use GenServeradd to a module?Answer
The behaviours and default callbacks of the GenServer contract
use GenServer sets up the behaviour, its defaults and the child spec; the callbacks are yours.
-
Which callback answers a
GenServer.call/2?Answer
handle_call/3
A call is handled by handle_call/3, which returns {:reply, answer, state}.
-
What does
handle_cast/2return?Answer
{:noreply, state}
A cast has no caller waiting, so the callback returns {:noreply, new_state}.
-
Why does
handle_continue/2exist?Answer
To do work after init without blocking the start
init returns {:ok, state, {:continue, msg}} and the runtime runs the work before other messages.
-
What does this program print?
defmodule C do use GenServer def start_link(_), do: GenServer.start_link(__MODULE__, 1, name: __MODULE__) def value, do: GenServer.call(__MODULE__, :value) @impl true def init(n), do: {:ok, n} @impl true def handle_call(:value, _from, n), do: {:reply, n, n} end {:ok, _} = C.start_link([]) IO.puts(C.value())Answer
1
The initial state is 1 and the call returns it unchanged.
-
What does this program print?
defmodule C do use GenServer def start_link(_), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__) def add, do: GenServer.cast(__MODULE__, :add) def value, do: GenServer.call(__MODULE__, :value) @impl true def init(n), do: {:ok, n} @impl true def handle_cast(:add, n), do: {:noreply, n + 1} @impl true def handle_call(:value, _from, n), do: {:reply, n, n} end {:ok, _} = C.start_link([]) C.add() IO.puts(C.value())Answer
1
The cast increments the state before the call reads it.
-
What does this program print?
defmodule S do use GenServer def start_link(_), do: GenServer.start_link(__MODULE__, :ready, name: __MODULE__) def stop, do: GenServer.call(__MODULE__, :stop) @impl true def init(state), do: {:ok, state} @impl true def handle_call(:stop, _from, state), do: {:stop, :normal, :bye, state} end {:ok, _} = S.start_link([]) IO.inspect(S.stop())Answer
:bye
The second element of {:stop, reason, answer, state} is the reason and the third is the answer.
-
What happens on a second
start_linkwith a name that is already registered?Answer
It returns {:error, {:already_started, pid}}
A name maps to one process; a second registration fails with :already_started.
-
What does
GenServer.cast/2return?Answer
:ok, as soon as the message is queued
A cast is asynchronous: the caller gets :ok and cannot see the new state.
-
A slow job sits in
init/1of a child. What does the supervisor see?Answer
The start blocks until init returns, and the start timeout can fire
init runs before the start returns, so a long init delays the supervisor; handle_continue moves the work.
Автор статьи: Arthur Isaev