All posts

Understanding Elixir GenServer

This and the other “Deck” posts are a repurposing of flashcard study decks to Q&A blog posts. Google was not showing love to this content as a set of flashcards and I didn’t want to delete them entirely, I hope you find it useful.

What is an Elixir GenServer?

It is a means of spawning an Elixir Process but with the added intention of keeping track of state. GenServer comes with a set of predefined callback functions to help with this.

What are the advantages of GenServer vs other process management tools?

  1. GenServers callback functions are standardized. Once you understand them, you understand how to work with any GenServer.
  2. GenServers provide a mechanism for keeping track of state.
  3. GenServers provide the ability to execute asynchronously or synchronously.
  4. GenServers provide functionality for tracing and error reporting.

Are GenServer processes supervised by a parent process?

They can be, but it’s not required.

Do all GenServer callback functions need to be implemented in each GenServer?

No. Each GenServer only needs to implement the callback functions it needs. The only required callback function is init.

What is the init callback function used for?

This is invoked whenever the server is started. It can be used to pass initial state to the GenServer.

What is the handle_call callback function used for?

This callback is used whenever you want to handle synchronous messages to the server. It is invoked through GenServer.call.

What is the handle_cast callback function used for?

This callback is used whenever you want to handle asynchronous messages to the server. It is invoked through GenServer.cast.

What is the handle_info callback function used for?

This is used for all other messages to the server, for example process crash messages. It is invoked in different ways including the Kernel.send function or Process.monitor.

How many GenServer callback functions exist and what are they?

  1. init, handle_call, handle_cast, handle_info, code_change, format_status, handle_continue, terminate.

Are GenServers used for code organization, for handling mutable state, or for providing concurrency?

GenServers are used to for handling of mutable state and for providing concurrency. GenServer’s are not used for code organization.