2

I have an object with vars that will change only from inside the object and during the initialisation / construction of the object instance.

Can the same object constructor be run twice by accident in a race condition scenario? Or Scala offers proper checks to ensure it can only be run once?

V-Lamp
  • 1,630
  • 10
  • 18
  • 1
    A Scala `object` is a static singleton instance. How could the constructor by run twice? – jwvh Dec 05 '17 at 21:15
  • 2
    When two threads access the same, non-initialised object, forcing it to be initialised at that time, (hopefully not) two times. – V-Lamp Dec 05 '17 at 21:23
  • Based on this https://stackoverflow.com/questions/29471402/what-is-the-proper-way-to-initialize-singleton-element-in-a-thread-safe-way-in-s and another thread I read sounds like you have to manage the locking/synchronization yourself. – ameer Dec 05 '17 at 22:18
  • @ameer That question wasn't about `object`s. – sepp2k Dec 05 '17 at 22:49
  • Usually this concern arises when you are using singletons (that, as mentioned, don't require any pattern in Scala and can be implemented with the `object` keyword – which uses locking to protect against this scenario). Can you post a snippet of code that could cause this to happen? – stefanobaghino Dec 06 '17 at 06:21

1 Answers1

2

Yes, it's safe: the constructor runs in a static initializer. See e.g. http://blogs.tedneward.com/patterns/singleton-scala/.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487