GenServer
Init and start
A GenServer is a behaviour: the runtime owns the loop, and your module fills in the callbacks. start_link/0 starts the process and registers it under the module name, and init/1 answers the initial state. Save this module as counter.erl.
-module(counter).
-behaviour(gen_server).
-export([start_link/0, start/0, increment/0, value/0, stop/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, 0, []).
start() ->
{ok, _Pid} = start_link(),
ok.
increment() ->
gen_server:cast(?MODULE, increment).
value() ->
gen_server:call(?MODULE, value).
stop() ->
gen_server:stop(?MODULE).
init(State) ->
{ok, State}.
handle_call(value, _From, State) ->
{reply, State, State}.
handle_cast(increment, State) ->
{noreply, State + 1}.
handle_info(_Msg, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
The start/0 function hides the pid that start_link/0 answers, so the shell session stays free of a value that changes on every run. Start the server, cast two increments, read the state with a call, and stop it.
erlc counter.erl
erl
1> counter:start().
ok
2> counter:increment().
ok
3> counter:increment().
ok
4> counter:value().
2
5> counter:stop().
ok
6> whereis(counter).
undefined
Callbacks
handle_call/3 answers a synchronous call: it receives the request, the caller and the state, and returns {reply, Value, NewState}. The call blocks the caller until the reply comes back, which is why value/0 can answer with a plain number. handle_cast/2 answers an asynchronous cast with {noreply, NewState}: the sender does not wait, so increment/0 answers ok at once and the state changes a moment later.
The two callbacks in the module above show the shape. handle_call matches the atom value, and handle_cast matches the atom increment; any other request would crash the server, which is the point of a precise match.
Info messages
A plain message sent with the exclamation mark lands in handle_info/2, together with timeouts and monitor messages. Return {noreply, NewState} and the loop continues. The clause above ignores the message and keeps the state, which is the safe default for a message the server does not understand.
Terminate
terminate/2 runs when the server stops, and it is the place to close a file or a socket. gen_server:stop/1 asks the server to stop and waits until terminate has returned. The call answers ok, and the registered name is gone, as the last session line shows.
Next: Supervisors
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a GenServer?
Answer
A behaviour whose loop the runtime owns
You fill in the callbacks;
gen_serverruns the receive loop and the protocol. -
What does
init/1answer?Answer
{ok, State}The initial state comes back as
{ok, State}, and the loop starts with it. -
What does
{local, ?MODULE}instart_link/0do?Answer
Registers the server under the module name
The name lets the API functions send to the atom
counterwithout keeping a pid. -
Which callback answers a synchronous call?
Answer
handle_call/3handle_call/3gets the request, the caller, and the state, and returns a reply. -
What does
handle_call(value, _From, State)return here?Answer
{reply, State, State}It replies with the state and keeps the same state, so
value/0answers the count. -
What does
handle_cast/2return for a successful cast?Answer
{noreply, NewState}A cast has no reply, so the callback answers
{noreply, NewState}. -
Does
counter:increment()wait for the state to change?Answer
No, a cast is asynchronous
gen_server:cast/2sends and returns at once; the state changes when the server handles the message. -
Which messages reach
handle_info/2?Answer
Plain messages, timeouts, and monitor messages
Everything that is not a call or a cast arrives at
handle_info/2. -
What does
counter:value()answer after two increments?Answer
2Each cast adds one to the state, and the call replies with the current state.
-
What does
whereis(counter)answer aftergen_server:stop/1?Answer
undefinedStopping removes the registered name, so
whereis/1finds nothing.
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