[erlang-questions] When to use gen_server?

eigenfunction emeka_1978@REDACTED
Thu Jan 12 19:34:29 CET 2012

I understand that, from a design pattern standpoint, it is cleaner to
use a gen_server to abstract away
boilerplate and not write the same "receive"/"send" primitives
everytime. But Garret said something that i was not aware of, even
after reading all the erlang books out there: "serialization of data
processing". Now i understand the definition of "gen_server" that is
written in the documentation.

On Jan 12, 5:54 pm, Garrett Smith <g...@REDACTED> wrote:
> On Thu, Jan 12, 2012 at 4:35 AM, eigenfunction <emeka_1...@REDACTED> wrote:
> >> If you don't need to serialize your data
> >> processing requests, don't bother with all that.
> > Could you pls elaborate more on that? I, Like the OP , sometimes
> > have a hard time making a difference between a gen_server and a normal
> > process,
> > and i end up using normal processes and think that i am doing
> > something wrong.
> > Can anyone give an example of a case where a gen_server is more useful
> > than a normal
> > process?
> As Robert succinctly put, a gen_server wraps a process. Use gen_server
> whenever you want to formalize your process behavior.
> Here's a simple low level use of an Erlang process:
>   spawn(fun() -> do_work() end)
> We do some work in an Erlang process and when we're done the process
> exits. Super simple.
> We can "formalize" the process by creating a module:
>   -module(workers).
>   start_work ->
>       spawn(fun() -> do_work() end).
> This hides the details of doing the work. You can document it, you can
> include it in an OTP app that can be used in different system
> configurations. Fantastic!
> Adding more features to our process-based work system is now a matter
> of adding new functions:
>   change_work_priority/2
>   get_work_status/1
>   stop_work/1
> To implement these, we'd go through the basic routine: use a loop
> function that receives messages, handle message sent from our exported
> functions, send replies to callers, etc. You'll see this in every
> Erlang textbook.
> But at that point, for the cost of a few extra lines of code, we're
> better off implementing a gen_server behavior. We can then use OTP
> supervisors to start and monitor the process. Even if we don't care
> about process restarts (e.g. temporary restart strategy), using OTP
> conventions will formalize the process life cycle.
> Garrett
> _______________________________________________
> erlang-questions mailing list
> erlang-questi...@REDACTED://erlang.org/mailman/listinfo/erlang-questions

More information about the erlang-questions mailing list