Skip to content

Instantly share code, notes, and snippets.

@adriansr
Last active February 2, 2017 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adriansr/db3f0e389d79318c306e8e1f96e3253c to your computer and use it in GitHub Desktop.
Save adriansr/db3f0e389d79318c306e8e1f96e3253c to your computer and use it in GitHub Desktop.
Akka actor creation/deletion race-condition
package adriansr.test
import scala.util.control.NonFatal
import akka.actor.{Actor, ActorRef, ActorSystem, InvalidActorNameException, Props}
case class Test(name: String, retries: Int, delay: Long)
case class Create(iter: Long, cfg: Test)
case class Remove(iter: Long, actor: ActorRef, cfg: Test)
class Actor1 extends Actor {
override def receive = {
case test: Test =>
self ! Create(0, test)
case Create(idx, test) =>
println(s"Creating $idx")
try {
val ref = context.actorOf(Props[Actor2], test.name)
self ! Remove(idx, ref, test)
} catch {
case _: InvalidActorNameException =>
throw new Exception(s"Race-condition reproduced after $idx iterations")
case NonFatal(e) =>
throw e
}
case Remove(idx, actor, test) =>
println(s"Removing $idx")
context.stop(actor)
Thread.sleep(test.delay)
self ! Create(idx+1, test)
case _ =>
}
}
class Actor2 extends Actor {
def receive = {
case _ =>
}
}
object RaceMain extends App {
val s = ActorSystem("Test")
val act = s.actorOf(Props[Actor1])
act ! Test("child", 1000, 2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment