Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a code thread safe in scala?

Tags:

scala

I have a code in scala that, for various reasons, have few lines of code that cannot be accessed by more threads at the same time.

How to easily make it thread-safe? I know I could use Actors model, but I find it a bit too overkill for few lines of code.

I would use some kind of lock, but I cannot find any concrete examples on either google or on StackOverflow.

like image 519
Karel Bílek Avatar asked Dec 01 '22 23:12

Karel Bílek


2 Answers

I think that the most simple solution would be to use synchronized for critical sections (just like in Java). Here is Scala syntax for it:

someObj.synchronized {
    // tread-safe part
}

It's easy to use, but it blocks and can easily cause deadlocks, so I encourage you to look at java.util.concurrent or Akka for, probably, more complicated, but better/non-blocking solutions.

like image 122
tenshi Avatar answered Dec 05 '22 06:12

tenshi


You can use any Java concurrency construct, such as Semaphores, but I'd recommend against it, as semaphores are error prone and clunky to use. Actors are really the best way to do it here.

Creating actors is not necessarily hard. There is a short but useful tutorial on actors over at scala-lang.org: http://www.scala-lang.org/node/242

like image 22
evilcandybag Avatar answered Dec 05 '22 06:12

evilcandybag