Thursday, January 22, 2015

Primes computation : From home made akka actors based solution to akka-stream

Available on github, Primes is a library dedicated to primes number computation, it is fully generic and can work with various numeric types (Int, Long, BigInt for example). This library generates CheckedValue instances which contains the just tested numeric value, it tells you if it is prime number or not, gives you its position and the number of digit it contains. The fact that it computes the prime position, or not prime position, implies that the computation starts from the beginning or from a previous persisted state (previous highest prime CheckedValue and not prime CheckedValue).

In January 2014,

I spent some times writing an actor based primes computation algorithm, it was not a very easy task because it implies to manage myself many things :
  • back pressure management,
  • parallelism,
  • reordering results.

The full source code of this old implementation is available here.

Now, one year later,

it was time to look at something else, back pressure, results ordering, parallelism, ... are too common patterns with actors that we shouldn't have to deal with them directly, it is up to the framework to provide us with the right solution.

Akka-stream brings us a great abstraction, for them, and the result becomes quite easier to read and to understand. back-pressure is automatically taken into account, parallel processing and ordering are just done through mapAsync call instead of just a map call.

The full source code of this new implementation is available here.

Now let's give place to the code, and just compare NEW versus OLD code :

NEW : Akka-stream actors primes computation

Check this to see how to use it, for example directly from the scala console (sbt console).

OLD : Akka actors primes computation

From performance point of view

Some "naive" raw performance results ("sbt test" to try yourself) :

No comments:

Post a Comment