Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Naïve parallelization of the Eratosthenes sieve using Akka
import akka.actor._
object SimpleSieve extends App {
val MaxNumber = 500000
case object NoMoreCandidates
class Filter extends Actor {
private var prime: Int = _
override def receive: Receive = {
case NoMoreCandidates =>
println("No more candidates")
println(s"Spent just ${System.currentTimeMillis() - start} millis")
System.exit(0)
case firstCandidate: Int =>
prime = firstCandidate
println(s"$prime found")
context.become(filtering(context.actorOf(Props[Filter])))
}
private def filtering(successor: ActorRef): Receive = {
case candidate: Int if candidate % prime == 0 => // Drop candidate
case other => successor ! other
}
}
val start = System.currentTimeMillis()
val system = ActorSystem("sieve")
val sieve = system.actorOf(Props[Filter])
(2 to MaxNumber).foreach(sieve ! _)
sieve ! NoMoreCandidates
system.awaitTermination()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment