对象级别的 Val 和 Scala 中的线程安全 [英] Val at object level and thread safety in Scala

查看:180
本文介绍了对象级别的 Val 和 Scala 中的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在查看的现有代码库中偶然发现以下代码.还有其他类似的调用将值设置"为myService"等.确认以下部分不是线程安全的,因为 myService 不是本地"并且两个线程同时进入 createUser 并同时调用myService.newUser"时间会破坏后续的persona.firstName和persona.lastName等,这个理解正确吗?

Stumbled upon following code in an existing codebase I am looking at. there are other similar calls which "set" values to "myService' etc. Confirming that following piece isn't threadsafe given myService is not "local" and two threads entering createUser at the same time and calling "myService.newUser" at the same time will corrupt the subsequent persona.firstName and persona.lastName etc. Is this understanding correct?

object WFService {
  lazy private val myService = engine.getMyService     

def createUser(persona: Persona): String = {
    val user = myService.newUser(persona.id.toString)
    persona.firstName.map(n => user.setFirstName(n))
    persona.lastName.map(n => user.setLastName(n))

推荐答案

Scala 中的惰性 val 是线程安全的 [1].您无需担心来自不同线程的多次调用会导致 RHS 被执行两次.

Lazy vals in Scala are thread safe [1]. You don't need to worry about multiple calls from different threads resulting in the RHS being executed twice.

既然你有一个对象,那么你也只有一个 WFService 实例.

Since you have an object, you only have one instance of WFService too.

[1] http://code-o-matic.blogspot.co.uk/2009/05/double-checked-locking-idiom-sweet-in.html

这篇关于对象级别的 Val 和 Scala 中的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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