|
| 1 | +import scala.actors.ActorSystem._ |
| 2 | +import scala.actors.Actor._ |
| 3 | +import scala.actors.{Actor, RichActor, ActorRef} |
| 4 | +import scala.util.continuations._ |
| 5 | +import java.util.concurrent.{TimeUnit, CountDownLatch} |
| 6 | +import scala.collection.mutable.ArrayBuffer |
| 7 | + |
| 8 | +class TestRichActor extends RichActor { |
| 9 | + |
| 10 | + def handle = { case v: Int => Test.append(v); Test.latch.countDown() } |
| 11 | + |
| 12 | +} |
| 13 | + |
| 14 | +object Test { |
| 15 | + val NUMBER_OF_TESTS = 5 |
| 16 | + |
| 17 | + // used for sorting non-deterministic output |
| 18 | + val buff = ArrayBuffer[Int](0) |
| 19 | + val latch = new CountDownLatch(NUMBER_OF_TESTS) |
| 20 | + val toStop = ArrayBuffer[ActorRef]() |
| 21 | + |
| 22 | + def append(v: Int) = synchronized { |
| 23 | + buff += v |
| 24 | + } |
| 25 | + |
| 26 | + def main(args: Array[String]) = { |
| 27 | + // plain scala actor |
| 28 | + val a1 = actor { |
| 29 | + reset {react { case v:Int => Test.append(v); Test.latch.countDown() }} |
| 30 | + } |
| 31 | + a1 ! 100 |
| 32 | + |
| 33 | + // simple instantiation |
| 34 | + val a2 = actorOf(new TestRichActor) |
| 35 | + a2.start() |
| 36 | + a2 ! 200 |
| 37 | + |
| 38 | + toStop += a2 |
| 39 | + // actor of with scala actor |
| 40 | + val a3 = actorOf(actor{ |
| 41 | + reset {react { case v:Int => Test.append(v); Test.latch.countDown() }} |
| 42 | + }) |
| 43 | + a3 ! 300 |
| 44 | + |
| 45 | + // using the manifest |
| 46 | + val a4 = actorOf[TestRichActor].start() |
| 47 | + a4 ! 400 |
| 48 | + |
| 49 | + toStop += a4 |
| 50 | + // deterministic part of a test |
| 51 | + |
| 52 | + // creation without actorOf |
| 53 | + try { |
| 54 | + val a3 = new TestRichActor |
| 55 | + a3 ! -1 |
| 56 | + } catch { |
| 57 | + case e => println("OK error: " + e) |
| 58 | + } |
| 59 | + |
| 60 | + // actorOf double creation |
| 61 | + try { |
| 62 | + val a3 = actorOf { |
| 63 | + new TestRichActor |
| 64 | + new TestRichActor |
| 65 | + } |
| 66 | + a3 ! -1 |
| 67 | + } catch { |
| 68 | + case e => println("OK error: " + e) |
| 69 | + } |
| 70 | + |
| 71 | + // actorOf nesting |
| 72 | + try { |
| 73 | + val a5 = actorOf { |
| 74 | + val a6 = actorOf[TestRichActor] |
| 75 | + new TestRichActor |
| 76 | + } |
| 77 | + a5.start() |
| 78 | + a5 ! 500 |
| 79 | + toStop += a5 |
| 80 | + } catch { |
| 81 | + case e => println("Should not throw an exception: " + e) |
| 82 | + } |
| 83 | + |
| 84 | + // output |
| 85 | + latch.await(10, TimeUnit.MILLISECONDS) |
| 86 | + if (latch.getCount() > 0) { |
| 87 | + println("Error: Tasks have not finished!!!") |
| 88 | + } |
| 89 | + |
| 90 | + buff.sorted.foreach(println) |
| 91 | + toStop.foreach(_.stop()) |
| 92 | + } |
| 93 | +} |
0 commit comments