The following example shows that one can use a mutable variable as message sended to an Actor. Does Scala Actor process mutable messages and immutable messages differently? If not, why people say that immutability is the reason that Scala is good for concurrency?
import scala.io._
import scala.actors._
import Actor._
def getPageSize(url : String) = Source.fromURL(url).mkString.length
var abc = "http://www.verycd.com"
def getPageSizeConcurrently() = {
abc = "http://www.twitter.com" // changing value
val caller = self
actor { caller ! (abc, getPageSize(abc)) }
receive {
case (url, size) =>
println("Size for " + url + ": " + size)
}
}
getPageSizeConcurrently
Update: I got a very nice reply at here.
I think your question is a little strange, maybe you are wondering why Scala still has mutable variable / data structure if immutable one is better for concurrency?
Yes, immutability is good for concurrency and is easier to reason about your code just as others answered.
But that does not mean mutable is useless or inherently bad, sometimes implementation using mutable
varor data structure is easier or maybe running faster in some specific case.Scala does not force you doing everything imutable like Haskell, instead it provide and encourage you use immutable
valand data structures.But it also provide you mutable ones, make sure it is there if you really need it.
So, yes. Scala/Akka actor will process mutable messages the same as immutable ones, but you should not do it if you didn’t have a good reason.
And if you’re using
var, you should have a good reason too, and should limit their scop.