事件驱动的递归参与者是否有可能出现 StackOverflow 错误?
正如评论中所说, Combinatiors.loop
旨在在重复执行 Actor 的主体时避免堆栈溢出。
但是,当消息处理实际上[几乎]总是计划执行时,对事件驱动的参与者(react
)使用loop
有什么意义吗?在专用的线程池中?主体的简单递归调用似乎是一个更有效的选择。
方法Reactor.seq
(由Combinatiors.loop
调用)定义如下:
private[actors] def seq[a, b](first: => a, next: => b): Unit = {
val killNext = this.kill
this.kill = () => {
this.kill = killNext
// to avoid stack overflow:
// instead of directly executing `next`,
// schedule as continuation
scheduleActor({ case _ => next }, null)
throw Actor.suspendException
}
first
throw new KillActorControl
}
假设,直接调用next
。在这种情况下,react
立即执行,消息处理已安排,并且 Actor 已暂停。没有堆栈溢出的空间...
我哪里错了?
As it's said in the comments, Combinatiors.loop
of the standard actors library is intended to save you from stack overflows, when the body of an actor is repeatedly executed.
But, does it make any sense to use loop
for an event-driven actors (react
), when message handling is, in fact, [almost] always scheduled to be executed in a dedicated thread pool? Simple recursive call of the body seem to be a more efficient option.
Method Reactor.seq
(called by Combinatiors.loop
) is defined as follows:
private[actors] def seq[a, b](first: => a, next: => b): Unit = {
val killNext = this.kill
this.kill = () => {
this.kill = killNext
// to avoid stack overflow:
// instead of directly executing `next`,
// schedule as continuation
scheduleActor({ case _ => next }, null)
throw Actor.suspendException
}
first
throw new KillActorControl
}
Let's assume, next
is called directly. In this case, react
is executed immediately, message handling is scheduled, and the actor is suspended. No room for stack overflows...
Where am I wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
loop
是一种通用构造,可用于基于线程和事件驱动的参与者。如果您尝试递归地处理基于线程的参与者的消息,您将很快因堆栈溢出而结束(除非您的消息处理是尾递归的,并且可以优化)。关于事件驱动的参与者,你是绝对正确的 - 递归处理会更有效,只要特定于基于线程的参与者的堆栈溢出场景对于事件驱动的参与者无效(你甚至不应该进行递归可优化)。
loop
is a general-purpose construct, that can be used both for thread-based and event-driven actors. If you try to handle messages of a thread-based actor recursively, you will end up quickly with stack overflow (unless your message handling is tail recursive, and can be optimized).With regards to event-driven actors, you're absolutely right - recursive handling will be more effective, as long as stack overflow scenario specific for thread-based actors is not valid for event-driven ones (you even shouldn't make the recursion optimizable).