Search code examples
actorakka

How to determine the number of actors to spawn in akka?


I have recently started looking into the Akka 2.0 framework and was able to get some code running, spawning actors that perform simple oracle database calls, performing simple calculations and whatnot, nothing in production however.

What I want to know, is there a general rule of thumb or best practice to determining how many actors to spawn for certain types of tasks? Say for example, I have a connection pool of 200 jdbc connections, Do I create an actor to represent each connection? Do I create a handful of them and use a round-robin approach?

Thanks.


Solution

  • Note that numberOf(actors) != numberOf(threads).

    You should create an actor for every entity that would otherwise share mutable state across threads. The whole thing about the actor model is that it shall isolate mutable state so that only immutable messages get exchanged between the actors. The result is that you don't need any locks anymore and you can easily reason about the thread safety of your program because all mutable state is isolated in actors and you can rely on the framework to properly pass the memory barrier whenever required, e.g. when switching an actor from one thread to another.

    The number of threads is a different subject: This depends on the number of cores and the blocking coefficient for each thread, i.e. the percentage of time it spends waiting for other threads or the I/O subsystem. For example, if your actors are doing CPU intensive calculations (e.g. calculating Pi) then the blocking coefficient will be close to 0%. If however your actors are doing mostly I/O, you can easily assume a blocking coefficient of 90% or more.

    Finally, the number of threads can be calculated like this:

    int threads = Runtime.getRuntime().availableProcessors() * 100 / (100 - blockingCoefficient)
    

    where blockingCoefficient represents an integer percentage between 0 and 99 inclusively.