## Thursday Nov 01, 2007

### Concurrency with Scala (was Concurrency with Erlang)

Steve Vinosky has written some really interesting articles on Erlang concurrency and Erlang reliability. I think i am going to buy that book on Erlang he recommends.

After i read his article on concurrency i wondered if the same (contrived but instructive) example he presents could be written in Scala and how it would compare, if anything it is a good exercise in learning.

Here is the simple non-concurrent (tail call) recursive pow function in Scala:

`def pow(n: int, m: int): BigInt = {    def _pow(m: int, acc: BigInt): BigInt  = m match {        case 0 => acc        case _ => _pow(m - 1, acc \* n)    }     _pow(m, 1)}`

and here is the concurrent cpow function using Scala's event-based actors:

`def cpow(n: int, m: int): BigInt = {    val actors = for (_ <- List.range(0, m)) yield             actor { react { case x: int => sender ! x } }    actors foreach ( a => a ! n )    (actors foldLeft BigInt(1)) { (t , a) => self ? match { case x: int => t \* x } }}     `

The value actors, which is a list of m actors, is obtained using list comprehension. As in Steve's example each actor just pings back the value it receives from the sender. Then a message is sent to each actor with the value of n. Finally all the values received from the actors are multipled together (as BigInt types) using the foldLeft function. Rather elegant! and similar in size to the Erlang code.

I measured the time it took for both functions to calculate 502000 on my Acer Ferrari 3400 laptop running Solaris, Java SE 5, and Scala 2.6.0. The pow function took 17.86 ms and the cpow function took 81.28 ms.

Below I re-iterate one of Steve's final points with a slight modification:

..., many developers are comfortable with OO programming. I’d like to advise such developers not to let Erlang’s or Scala's functional nature scare you away, ...

Given that Scala is a hybrid object-oriented and functional programming language it can enable developers to smoothly transition between the imperative and functional programming styles in  small manageable steps i.e. Scala is less scary than it might initially appear.

sandoz

##### Archives
Sun Mon Tue Wed Thu Fri Sat « June 2016 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 30 Today
##### News

No bookmarks in folder