alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (ActorTest.scala)

This example Scala source code file (ActorTest.scala) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Scala by Example" TM.

Learn more about this Scala project at its project page.

Java - Scala tags/keywords

actor, actortest, countdownlatch, int, numofmessages, numofmessagesperthread, numofthreads, should, speclite, threading, threads, throwable

The ActorTest.scala Scala example source code

package scalaz
package concurrent

import collection.mutable
import java.util.concurrent._
import ConcurrentTest._

object ActorTest extends SpecLite {
  val NumOfMessages = 1000
  val NumOfThreads = 4
  val NumOfMessagesPerThread = NumOfMessages / NumOfThreads
  implicit val executor = Executors.newFixedThreadPool(NumOfThreads)

  "code executes async" in {
    val latch = new CountDownLatch(1)
    val actor = Actor[Int]((i: Int) => latch.countDown())
    actor ! 1
    assertCountDown(latch, "Should process a message")
  }

  "code errors are catched and can be handled" in {
    val latch = new CountDownLatch(1)
    val actor = Actor[Int]((i: Int) => 100 / i, (ex: Throwable) => latch.countDown())
    actor ! 0
    assertCountDown(latch, "Should catch an exception")
  }

  "actors exchange messages without loss" in {
    val latch = new CountDownLatch(NumOfMessages)
    var actor1: Actor[Int] = null
    val actor2 = Actor[Int]((i: Int) => actor1 ! i - 1)
    actor1 = Actor[Int] {
      (i: Int) =>
        if (i == latch.getCount) {
          latch.countDown()
          latch.countDown()
          if (i != 0) actor2 ! i - 1
        }
    }
    actor1 ! NumOfMessages
    assertCountDown(latch, "Should exchange " + NumOfMessages + " messages")
  }

  "actor handles messages in order of sending by each thread" in {
    val latch = new CountDownLatch(NumOfMessages)
    val actor = countingDownActor(latch)
    for (j <- 1 to NumOfThreads) fork {
      for (i <- 1 to NumOfMessagesPerThread) {
        actor ! (j, i)
      }
    }
    assertCountDown(latch, "Should process " + NumOfMessages + " messages")
  }

  def countingDownActor(latch: CountDownLatch): Actor[(Int, Int)] = Actor[(Int, Int)] {
    val ms = mutable.Map[Int, Int]()

    (m: (Int, Int)) =>
      val (j, i) = m
      if (ms.getOrElse(j, 0) + 1 == i) {
        ms.put(j, i)
        latch.countDown()
      }
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala ActorTest.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.