How to make safe code in scala?

I have code in scala that, for various reasons, has several lines of code that cannot be accessed by more threads at once.

How easy is it to make it thread safe? I know that I can use the Actors model, but I find it too redundant for a few lines of code.

I would use some kind of lock, but I can not find specific examples in either google or StackOverflow.

+4
source share
4 answers

I think the easiest solution would be to use synchronized for critical partitions (as in Java). Here is the Scala syntax for it:

 someObj.synchronized { // tread-safe part } 

It is easy to use, but it blocks and can easily cause deadlocks, so I recommend that you look at java.util.concurrent or Akka for perhaps more complex, but better / non-blocking solutions.

+15
source

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

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

+3
source

If it is really very simple, you can use synchronization: http://www.ibm.com/developerworks/java/library/j-scala02049/index.html

Or you can use some of the classes from the parallel package in jdk: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html

If you want to use actors, you must use Akka actors (they will replace scala members in the future), see here: http://doc.akka.io/docs/akka/2.0.1/ . They also support features such as FSM (state machine) and STM (software transactional memory).

+1
source

In general, try using pure "functions" or methods with immutable data structures that should help ensure thread safety.

0
source

Source: https://habr.com/ru/post/1413914/


All Articles