How to make a code thread safe in scala?

后端 未结 4 779
[愿得一人]
[愿得一人] 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:36

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

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

    If you want to use actors, you should use akka actors (they will replace scala actors in the future), see here: http://doc.akka.io/docs/akka/2.0.1/. They also support things like FSM (Finite State Machine) and STM (Software Transactional Memory).

    0 讨论(0)
  • 2021-01-14 02:45

    In general try to use pure 'functions' or methods with immutable data structures that should help with thread safety.

    0 讨论(0)
  • 2021-01-14 02:48

    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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题