2017-08-21 1 views
1

Je suis tombé sur ce code et je me demande ce que fait CallingThreadDispatcher. Je peux commenterQue fait CallingThreadDispatcher?

val dispatcherId = CallingThreadDispatcher.Id 
val props = Props[Greeter].withDispatcher(dispatcherId) 

et ce test fonctionne toujours

class GreeterTest extends TestKit(testSystem) 
    with WordSpecLike 
    with MustMatchers 
    with StopSystemAfterAll { 

    "The Greeter" must { 
    "say Hello World! when a Greeting(\"World\") is sent to it" in { 
     val dispatcherId = CallingThreadDispatcher.Id 
     val props = Props[Greeter].withDispatcher(dispatcherId) 
     val greeter = system.actorOf(props) 
     EventFilter.info(message = "Hello World!", occurrences = 1).intercept { 
     greeter ! Greeting("World") 
     } 
    } 
    } 
} 

object GreeterTest { 
    val testSystem = { 
    val config = ConfigFactory.parseString("""akka.loggers = [akka.testkit.TestEventListener]""") 
    ActorSystem("testSystem", config) 
    } 
} 

Alors qu'est-ce que CallingThreadDispatcher faire? et pourquoi en avons-nous besoin?

Répondre

2

La documentation CallingThreadDispatcher est assez bonne:

* Dispatcher which runs invocations on the current thread only. This 
* dispatcher does not create any new threads, but it can be used from 
* different threads concurrently for the same actor. The dispatch strategy is 
* to run on the current thread unless the target actor is either suspendSwitch or 
* already running on the current thread (if it is running on a different 
* thread, then this thread will block until that other invocation is 
* finished); if the invocation is not run, it is queued in a thread-local 
* queue to be executed once the active invocation further up the call stack 
* finishes. This leads to completely deterministic execution order if only one 
* thread is used. 

Il est utilisé dans les tests unitaires, car il est pratique pour les acteurs d'avoir déterministe pour d'exécution lorsque vous testez une unité particulière du code . Comme vous le voyez, ce n'est pas obligatoire pour le test que vous exécutez et fonctionne également sans.