jswny

jswny

Why does this simple GenServer timeout?

I’ve condensed the problem I found while playing around with GenServers (I don’t know much about OTP yet) into the following script:

defmodule Test do
  use GenServer

  def handle_call({:work, item}, _from, _state) do
    IO.puts "Processing item #{item}..."
    :timer.sleep(3000)
    {:reply, "Done processing item #{item}!", []}
  end
end

GenServer.start_link(Test, [], name: Test)

Task.start(fn -> GenServer.call(Test, {:work, 1}, 5000) end)
Task.start(fn -> GenServer.call(Test, {:work, 2}, 5000) end)

:timer.sleep(15000)

When I run this, I get the following:

C:\Users\Joe\test>elixir script.exs
Processing item 1...
Processing item 2...

12:17:24.056 [error] Task #PID<0.77.0> started from #PID<0.69.0> terminating
** (stop) exited in: GenServer.call(Test, {:work, 2}, 5000)
    ** (EXIT) time out
    (elixir) lib/gen_server.ex:737: GenServer.call/3
    (elixir) lib/task/supervised.ex:85: Task.Supervised.do_apply/2
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Function: #Function<1.117183472 in file:script.exs>
    Args: []

It seems to me that this should never timeout because handle_call only sleeps for 3000 milliseconds, and the call is allotted 5000 milliseconds of timeout time. So then, why do I get a timeout in the second call?

Most Liked

peerreynders

peerreynders

Based on GenServer.reply/2:

defmodule Test do
  use GenServer

  def handle_call({:work, item}, from, state) do
    IO.puts "Processing item #{item}..."
    Process.send_after self(), {:reply, from, item}, 3_000
    {:noreply, state}
  end

  def handle_info({:reply, from, item}, state) do
    GenServer.reply from, "Done processing item #{item}!"
    {:noreply, state}
  end

end

GenServer.start_link(Test, [], name: Test)

Task.start(fn -> IO.puts (GenServer.call Test, {:work, 1}, 5_000) end)
Task.start(fn -> IO.puts (GenServer.call Test, {:work, 2}, 5_000) end)

:timer.sleep(15_000)

.

$ elixir test.exs
Processing item 1...
Processing item 2...
Done processing item 1!
Done processing item 2!
$

So GenServer doesn’t have to reply to a call immediately. It can store “intermediate results” in its own state - for example when it’s still “waiting” for results from other processes while not being blocked so that it can accept new requests even before the other work is completely done.

The one big drawback to GenServer.call/3 is that it blocks the client process. So when processes “co-operate” it isn’t that uncommon to use GenServer.cast/2 instead by simply including a return pid (or from) in the request message proper, for the eventual result message - that way none of the processes ever have to be blocked - they just process the (cast) messages (and results) as they come in.

PS: version that gets the GenServer state actively involved:

defmodule Test do
  use GenServer

  def handle_call({:work, item}, from, old_state) do
    state = add_result old_state, from, item
    IO.puts "Processing item #{item}..."
    Process.send_after self(), {:reply, from}, 3_000
    {:noreply, state}
  end

  def handle_info({:reply, from}, old_state) do
    {item, state} = pop_result old_state, from
    GenServer.reply from, "Done processing item #{item}!"
    {:noreply, state}
  end

  defp add_result(state, from, item),
    do: Map.put state, from, item

  defp pop_result(state, from) do
    item = state[from]
    new_state = Map.delete state, from
    {item, new_state}
  end

end

GenServer.start_link(Test, %{}, name: Test)

Task.start(fn -> IO.puts (GenServer.call Test, {:work, 1}, 5_000) end)
Task.start(fn -> IO.puts (GenServer.call Test, {:work, 2}, 5_000) end)

:timer.sleep(15_000)

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement