0x1a – This is how Erlang makes sense, pt. 2

This is part 2 of a series about Erlang. The final part 3 will be published next week here.

Erlang/OTP didn’t come out of thin air. Quite the opposite – seldom you see a language and a platform where the implementation mirrors the intention that closely.


But how do Erlang applications share a global state then? One way to synchronize access to a ressource is by a message queue, where each message helds the type of requested access. And as Erlang/OTP was about an efficient parallel server infrastructure, this is easy to add on – after all, all servers implement some kind of message queue; even though some don’t know about that because they don’t care for the underlying network infrastructure.

So to have some global state you start an Erlang process dedicated to manage exactly that state information and nothing else and have it wait for and evaluate messages and send back answers.

Note: This is only about global states. To adjust a state over time you usually do some tail recursion like this:

foo(State, In) ->
case In of
  done -> done;
  _ -> foo(calculateNewState(State, In))

Efficiency: Pattern matching

This message passing would add some runtime penalty on the implementation, one would expect. That is, of course, unless everything works really fast.

Erlang was not stupid enough to request a specified fixed length message format (as Windows was, at a time). Instead it allows you to pass around everything which is an erlang object. Being immutable once created it is safe to pass it on as a reference and not as a value, i.e. only as a couple of bytes.

After sending a message the next step involved is understanding it. You usually have erlang patterns like this:

loop() ->
    {cmd, A, B, C} -> cmd_on(A,B,C), loop();
    stop           -> stop;
    _              -> io:format("Unknown input!~n"), loop(Port)

You see, pattern matching must be fast in Erlang, and let me tell you: it usually is, especially when using tuples instead of lists and symbols instead of strings.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s