Akka how to start the main task and block its completion?

I am trying to get started with akka in scala. In the main scala stream, I would like to start an actor’s acc, send him one message and block until this actor completes. What is the best way to do this?

For example, I have a test actor who just sends messages to himself several times:

class Incrementer() extends Actor {

  val maxMessages = 5
  var counter = 0

  def receive() = {
    case DoIncr() => {
      if (counter < maxMessages) {
        counter += 1
        self ! DoIncr()
      } else {
        self.stop()
      }
    }
  }
}

and it is called through:

val inc = actorOf(new Incrementer()).start()
val result = inc !! DoIncr()
println(result) // this should block this thread, but it doesn't seem to.

// do other stuff

This block takes just over 5000 ms to execute instead of what I expect is a few ms, so it seems to be related to the default timeout - and the program does not actually end. All I'm really trying to do is send message execution time x number of messages. What's going on here?

+3
source share
1

, !!, . 5- - , . Akka.

forward !, self.reply .

, Akka, , . .

:

import akka.actor._

object DoIncr

class Incrementer extends Actor {
  val maxMessages = 5
  var counter = 0

  def receive = {
    case DoIncr =>
      if (counter < maxMessages) {
        counter += 1
        self forward DoIncr
      } else {
        self.reply(()) // replying with () since we have nothing better to say
        self.stop()
      }
  }
}

, , idiomatic Scala. , Scala .

  • . object.
  • ,
  • Actor receive ; .
  • , case .
+4

All Articles