Stacking exception using Scala members and receiveWithin

After a while, this actor fills the 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 was not lucky to find this code in a Program in Scala.

+3
source share
2 answers

Yours is actnot tail recursive. You can change it as follows:

  @tailrec // in the presence of this annotation, the compiler will complain, if the code is not tail-recursive
  def act() = {
    receiveWithin(2000) {
      case Stop => println("stoping puller"); exit()
      case Noop => println("nothing happens")
      case TIMEOUT => doPull
    }
    act()
  }
+4
source

Well, he overflows the stacks for very obvious reasons; it is recursive, but not recursive. There are two options here:

Or : use a while loop:

def act() = 
  while(true) {
    receiveWithin(2000) {
      case Stop    => println("stoping puller"); exit()
      case Noop    => println("nothing happens")
      case TIMEOUT => doPull
    }
  }

Or : use loopand react(which has the added benefit of being scalable by disabling the actor from hanging one thread).

def act() = 
  loop {
    reactWithin(2000) {
      case Stop    => println("stoping puller"); exit()
      case Noop    => println("nothing happens")
      case TIMEOUT => doPull
    }
  }

Scala, , . , , , act.

+4

All Articles