How to make a code thread safe in scala?

后端 未结 4 780
[愿得一人]
[愿得一人] 2021-01-14 02:17

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?

4条回答
  •  再見小時候
    2021-01-14 02:52

    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.

提交回复
热议问题