Last active
February 2, 2017 16:55
-
-
Save adriansr/db3f0e389d79318c306e8e1f96e3253c to your computer and use it in GitHub Desktop.
Akka actor creation/deletion race-condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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