如何在 Scala 中使代码线程安全? [英] How to make a code thread safe in scala?

查看:80
本文介绍了如何在 Scala 中使代码线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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.

如何轻松使其成为线程安全的?我知道我可以使用 Actors 模型,但我发现它对于几行代码来说有点太过分了.

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.

我会使用某种锁,但我在 google 或 StackOverflow 上都找不到任何具体的例子.

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

推荐答案

我认为最简单的解决方案是将 synchronized 用于关键部分(就像在 Java 中一样).这是它的 Scala 语法:

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
}

它易于使用,但它会阻塞并容易导致死锁,所以我鼓励您查看 java.util.concurrentAkka 可能更复杂,但更好/非阻塞解决方案.

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.

这篇关于如何在 Scala 中使代码线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆