LoginSignup
8
9

More than 5 years have passed since last update.

scalaz - Actor

Posted at

scalaz(7.1.3)のActorを試してみた。

ソースコードはこちら。100行ない。

テストコードはこちら

使い方

scala> val a1 = Actor[Int] { x => println(x + 1) }
scala> a1 ! 1
2

一つずつ処理

アクターなので並列で実行しても大丈夫。

まず普通なら並列に書き込むとダメだが、

scala> var n = 1
scala> (1 to 1000).par.foreach { _ => n += 1 }
scala> n
// res17: Int = 974

一つずつ実行されるのでちゃんと書き込まれる。

scala> var n = 0
scala> var a2 = Actor[Unit] { _ => n += 1 }
scala> (1 to 1000).par.foreach { _ => a2 ! Unit }
scala> n
// res26: Int = 1000

処理をつなげる

scala> val a3 = Actor[String](println) contramap[Int] { "x is " + _ } contramap[Int] { _ + 1 }
scala> a3 ! 1
// x is 2

エラーハンドリング

コンストラクタの第二引数でonErrorが指定出来る。

scala> val a = Actor[Int]({ x => ??? }, { e => println(s"ERR is ($e)") })
scala> a ! 1
// ERR is (scala.NotImplementedError: an implementation is missing)

本当に最低限の機能しかないので、本格的にActor使うならAkka。

再帰的なNodeを使って1つずつスレッドセーフに実行できるようになっていて、コード読むと勉強になる。

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9