Jun 10, 2009

Actors

Concurrency is an interesting topic these days. Actually, it has been an interesting topic for a long time. Yet it is strange that many of us still only know of one way to write a concurrent program: using threads. This is not a bad approach - in fact it is the approach that seems to give the most control over how a program executes because it is close to the machine.

There are other models of concurrency that you can use. Being the ignorant boor that I am, I really only know about the actor model, however if you have the interest you can read about others here. I am not going to talk about those today, I will be telling you about actors.

While some may disagree, the main idea behind object-oriented programming is that there are objects which send messages to one another - in most OO languages, this involves calling the other objects' methods. Things like inheritance and encapsulation and all that are secondary - although no less important.

The actor model is the same thing. There are actors (instead of objects) which send messages to one another. The difference between actors and objects is that every actor is always running, and when it sends a message it does not wait for the message recipient to finish processing before it continues to execute. Let's illustrate this with an example:
method foo
call bar
.. do stuff which does not take a long time
end

method bar
.. do stuff that make take a long time
end
In a traditional OO language like C++, Java, or basically any other OO language that I've worked with, nothing will happen in foo until bar has finished. So foo ends up taking a long time to execute, even though nothing really in foo takes a long time.
With actors however, foo will have finished long before bar does. Why? Because after foo makes the call to bar, it just continues on executing in parallel with bar. Pretty neat eh?

That's pretty much all there is to actors. You can try playing around with them yourself by trying out Scala which has built-in support for actors and is not too far away from Java, or you can take a deeper plunge and try out Erlang. Unfortunately I do not have much experience with either language, in fact my experience with actors comes from a research project in university I did using a C++ library for actors. You can probably find libraries that implement the actor model for most modern languages, if you're not interested in learning a new language.

No comments: