1

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))
user2066049
  • 1,371
  • 1
  • 12
  • 26
  • It is val member so I would assume that there could be only one alignement to it. The second one should return error. – goral Apr 13 '14 at 20:38

2 Answers2

6

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.

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

sksamuel
  • 16,154
  • 8
  • 60
  • 108
  • 3
    For that matter, if it was a `val` instead of a `lazy val` it would still be thread-safe, as the body of an `object` is executed as a constructor and, as you say, it's a singleton. – Daniel C. Sobral Apr 14 '14 at 00:50
0

It is val member so I would assume that there could be only one alignement to it. The second one should return error.

As mentioned before lazy val's in Scala are thread-safe. Please refert to: Lazy Vals initialization

goral
  • 1,275
  • 11
  • 17