When to use gen_server in Erlang/OTP applications
Asked Answered
C

2

14

Having read Joe Armstrong's book and watched Kevin Smith screencasts I've built a simple OTP application comprised of a single gen_server and single supervisor, bundled together as an OTP application.

Now I'm looking at mochiweb and have created a sample project [helloworld] using the new_mochiweb.erl script. Browsing the source code I see it's not dissimilar from my sample OTP app [the OTP application is there, the supervisor is there] with one key difference .. the generated helloworld.erl and helloworld_web.erl files don't implement gen_server behaviour, they are just standard Erlang modules.

I was under the impression that using gen_server was the recommended way to go when building OTP application components. Why might mochiweb use OTP application and supervisor behaviours but eschew gen_server ?

Ciprian answered 31/8, 2009 at 20:14 Comment(0)
F
5

There is a gen_server, called mochiweb_socket_server. The generated modules are only "callback modules" for the gen_server to be called when recieveing an incoming request.

Funchal answered 31/8, 2009 at 20:32 Comment(0)
C
10

You use OTP/gen_servers for processes which are under a restart strategy - that is the restart of them is in your control.

That is not the case with processes representing connections to web browsers. If that process dies there is no way for the server to restart it - therefore running it under OTP is pointless.

Mochiweb (and Yaws) both use gen_servers to bind to the listening port and then spawn an unsupervised process to handle a new connection.

Carpentaria answered 31/8, 2009 at 21:48 Comment(2)
The stdlib application is an OTP application. When started, it does not have any running parts. It's a plain library application, there for the modules it loads, so other OTP applications can depend on it to get all its modules. So there are still reasons to use OTP when one just introduce modules.Halpern
Your right, I was being a bit slapdash in my language... You should package all your code up in the normal OTP manner using the directories and stuff - but sometimes the right thing to do is just spawn something rather than using a gen_server to start it.Carpentaria
F
5

There is a gen_server, called mochiweb_socket_server. The generated modules are only "callback modules" for the gen_server to be called when recieveing an incoming request.

Funchal answered 31/8, 2009 at 20:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.