[erlang-questions] The gen server simplified (how it works)

Mihai Balea mihai@REDACTED
Wed Apr 20 14:52:11 CEST 2011


On Apr 20, 2011, at 4:05 AM, Joe Armstrong wrote:
> 
> This is *why* we made the gen_server abstraction. You can write well-typed
> sequential code (the handle_call and init functions) to parametrize
> a concurrent behavior, ie you need to know nothing about concurrency to
> get the job done. We've "abstracted out" the concurrency.

I believe saying that we have "abstracted out concurrency" is a bit dangerous.

A better description would be gen_server builds a function call, rpc-like if you will,  abstraction on top of a message passing communication protocol, while at the same time synchronizing access to a resource by serializing requests. A bit pedantic, but, in my opinion, an important nuance to understand, since it has significant performance implications.

> Things become problematic when you do not entirely understand the abstraction.
> Maybe the abstraction is inappropriate for your needs. I have seen many examples
> of code where the gen_server *is* inappropriate. The acid test is "does the
> gen_sever code look like spaghetti" if the answer is yes then all you have done
> is shoe horn the applications into an inappropriate form. In this case
> you should ditch the gen_server and roll-your own.

The most common form of gen _server abuse I have seen (and I plead guilty of it myself) is attempting to turn it into something akin to a state machine. My rule of thumb is if your state record contains a field called state or something like it and you take different actions based on it, then it's time to re-factor into a gen_fsm. It's easy to get into this situation since things usually start simple and build up once more functionality is piled on. 

Mihai

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20110420/6385e28f/attachment.htm>


More information about the erlang-questions mailing list