使用 Scala actor 和 receiveWithin 时出现 Stackoverflow 异常
一段时间后,该演员填满了堆栈。可能的解决方案?
object Puller extends Actor {
def act() = {
receiveWithin(2000) {
case Stop => println("stoping puller")
exit()
case Noop => println("nothing happens")
act()
case TIMEOUT => doPull
act()
}
}
def doPull() = // stuff...
}
我很高兴在《Scala 编程》中找到这段代码。
After some time this actor fills out stack. Possible solutions ?
object Puller extends Actor {
def act() = {
receiveWithin(2000) {
case Stop => println("stoping puller")
exit()
case Noop => println("nothing happens")
act()
case TIMEOUT => doPull
act()
}
}
def doPull() = // stuff...
}
I'm unhappy to find this code in Programming in Scala.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
act
不是尾递归的。您可以按如下方式修改:Your
act
is not tail-recursive. You can modify it as follows:嗯,它的堆栈溢出有非常明显的原因;它是递归的,但不是尾递归的。这里有两个选项:
要么:使用 while 循环:
或:使用
loop
和react
(其中有通过将参与者与占用单个线程分离来实现可扩展的额外好处)。如果此代码存在于Scala 编程中,那么它可能更多地意味着概念验证,而不是可行的生产代码。事实上,根据记忆,它继续解释了如何避免递归
act
调用。Well, it stack overflows for very obvious reasons; it's recursive but not tail-recursive. There are two options here:
Either: Use a while loop:
Or: Use
loop
andreact
(which has the added benefit of being scalable by decoupling the actor from hogging a single thread).If this code exists in Programming in Scala, it's probably meant more as a proof-of-concept, rather than viable production code. In fact, from memory, it goes on to explain how the recursive
act
calls can be avoided.