What is the difference between while (true) and loop?

I do not get the actual (semantic) difference between the two "expressions".
They say that “loop” is suitable for “reaction” and “while (true)” for “receiving”, because “reaction” does not return, and “loop” is a function that calls the body again and again (this is the least I subtract from sources - I am not very familiar with the used "andThen"). “Receive” blocks one thread from the pool, “respond” - no. However, for a “reaction”, a thread is scanned to which a function can be attached.

So the question is, why can't I use "loop" with "receive"? It seems that it behaves differently (and better!) Than the "while (true)" option, at least this is what I observe in the profiler. Even stranger, the ping-pong call with "-Dactors.maxPoolSize = 1 -Dactors.corePoolSize = 1" with "while (true)" and "receive" blocks immediately (what would I expect), however, loop "and" receive ", it works without problems - in one thread - how is it?

Thanks!

+6
scala
source share
2 answers

The loop method is defined in the Actor object:

 private[actors] trait Body[a] { def andThen[b](other: => b): Unit } implicit def mkBody[a](body: => a) = new Body[a] { def andThen[b](other: => b): Unit = self.seq(body, other) } /** * Causes <code>self</code> to repeatedly execute * <code>body</code>. * * @param body the code block to be executed */ def loop(body: => Unit): Unit = body andThen loop(body) 

This is confusing, but it happens that the block that comes after the loop (the thing between { and } ) is passed to the seq method as the first argument, and a new loop with this block as the second argument.

As for the seq method, in the Actor we find:

 private def seq[a, b](first: => a, next: => b): Unit = { val s = Actor.self val killNext = s.kill s.kill = () => { s.kill = killNext // to avoid stack overflow: // instead of directly executing `next`, // schedule as continuation scheduleActor({ case _ => next }, 1) throw new SuspendActorException } first throw new KillActorException } 

So, a new loop is planned for the next action after the kill, then the block is executed, and then an exception of type KillActorException is thrown, which will cause the loop to repeat.

So, the while executes much faster than the loop , because it does not exclude any exceptions, does not execute scheduling, etc. On the other hand, the scheduler gets the opportunity to schedule something else between two loop executions.

+2
source share

The critical difference between while and loop is that while restricts iterations of the loop in the same thread . The loop construct (as described by Daniel) allows the actor subsystem to trigger reactions to any thread that it selects.

Therefore, using the receive combination inside while (true) binds the actor to a single thread. Using loop and react allows react to run support for many participants in a single thread .

+4
source share

All Articles