This assumes that you have set up Scala as per Setting up Scala IDE & using Maven plugins for Java developers.
Step 1: Add the “scala-actors” dependency to the pom.xml file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <encoding>UTF-8</encoding> <scala.version>2.11.6</scala.version> <scala.specs.version>2.11</scala.specs.version> </properties> <dependencies> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>${scala.version}</version> </dependency> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-actors</artifactId> <version>${scala.version}</version> </dependency> //....... <dependencies> |
Step 2: Scala’s primary concurrency construct is an actor. Actors are basically concurrent processes that communicate by exchanging messages. Create a simple “actor” based code as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.mytutorial import scala.actors.Actor._ object ActorsInScala extends App { val listOfNumbers: List[Int] = (1 to 3).toList val sender = self; //the main thread itself listOfNumbers.foreach { element => actor { val thread = Thread.currentThread().getName println(thread + " sending " + element); sender ! element //! means send to the sender } } listOfNumbers.foreach { msg => val thread = Thread.currentThread().getName receive { case _ => println(thread + " received " + msg) } } } |
The thread names are printed for clarity. The output will be as shown below.
1 2 3 4 5 6 7 8 |
ForkJoinPool-1-worker-13 sending 1 ForkJoinPool-1-worker-9 sending 3 ForkJoinPool-1-worker-11 sending 2 main received 1 main received 2 main received 3 |
Points to remember
1) The “scala-actors” library provides both asynchronous and synchronous sending of messages.
2) “!” is a send operator.
3) The “receive” method receives the message from the actors’ mailbox. Each actor has a mailbox to queue messages.
4) Actors are normal objects that can be created by instantiating subclasses of the “Actor” class.
1 2 3 4 5 6 7 8 9 10 11 |
class Consumer(msg: String, sender: Actor) extends Actor { def act() { while (true) { receive { case Sender => println("received") } } } } |