Created
March 24, 2016 19:59
-
-
Save arkadius/2c40fd3d7d6148665061 to your computer and use it in GitHub Desktop.
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
import akka.actor.{Actor, ActorSystem, Props, Stash} | |
import scala.concurrent._ | |
object AsyncRestart extends App { | |
val system = ActorSystem() | |
val actor = system.actorOf(Props(new AsyncRestartActor)) | |
actor ! "1" | |
actor ! "2" | |
actor ! "fail" | |
actor ! "3" | |
} | |
class AsyncRestartActor extends Actor with Stash { | |
import context.dispatcher | |
@scala.throws[Exception](classOf[Exception]) | |
override def preStart(): Unit = { | |
init() | |
} | |
@scala.throws[Exception](classOf[Exception]) | |
override def postRestart(reason: Throwable): Unit = {} // to avoid init before PreviousStopped | |
private def init(): Unit = { | |
Future { | |
blocking { | |
Thread.sleep(1000) | |
println("init done") | |
} | |
}.onComplete { _ => | |
self ! Initialized | |
} | |
} | |
override def receive: Receive = { | |
case PreviousStopped => | |
init() | |
case Initialized => | |
unstashAll() | |
context.become(initialized) | |
case msg => | |
stash() | |
} | |
private val initialized: Receive = { | |
case "fail" => | |
throw new Exception("failed") | |
case msg => | |
println(msg) | |
} | |
override def postStop(): Unit = { | |
Future { | |
blocking { | |
Thread.sleep(1000) | |
println("stop done") | |
} | |
}.onComplete { _ => | |
self ! PreviousStopped | |
} | |
super.postStop() | |
} | |
} | |
case object Initialized | |
case object PreviousStopped |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment