3

I've seen this operator being used a lot, I even use it every time I have the change. All the cool gems have this peace of code. But what about thread safety when using this operator?

GuidoMB
  • 2,191
  • 3
  • 25
  • 40
  • 1
    It is not inherently more or less thread-safe than `x = x || y`; that is, it is *not* thread-safe. (There may be some slight caveats based upon a particular implementation, but it involves a read-write pair with **no guarantee of atomicity *or* visibility**.) –  Dec 13 '12 at 05:15

1 Answers1

1

Like any other assignment, it's not truly thread-safe without a mutex. It might appear thread-safe-ish depending on the number of cores in your system. I've noticed that 4-core/8-thread systems have a lot more problems with many threads than a 2-core/2-thread system, so if you have access to one of those, use that to be sure you've got whatever solution you're trying right.

Write locks can be messy business, but it's the price you pay for living in a multi-threaded world.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    Don't dissemble -- thread-safe-ish == unsafe. – dbenhur Dec 13 '12 at 06:15
  • @Tadman - Are you sure this isn't a safe operation in MRI thanks to GIL? – pguardiario Dec 13 '12 at 07:59
  • It really depends on how the byte-code is generated and interpreted. Like `+=` or even `++` in other languages, it's implemented as load, test, and store. If there's an opportunity for interruption between those, then it's not thread safe without a lock. – tadman Dec 13 '12 at 15:42
  • @dbenhur I was just trying to communicate that it might look safe on machines with only two threads, but is actually not safe as can be demonstrated on other systems with more. – tadman Dec 13 '12 at 15:42
  • So basically if I deploy my Rails app using JRuby I might get into trouble. (I don't know how this operator is implemented in the JVM). – GuidoMB Dec 13 '12 at 16:51
  • If you're using threads and you need to ensure something is never initialized twice, you'll *need* to use a [Mutex](http://apidock.com/ruby/Mutex) write lock to be sure that doesn't happen. It's not especially difficult to layer this in, but it does mean you'll have to be more careful. It's likely implemented the same way. The JVM won't make things magically thread safe. In fact, the opposite is more likely to occur, where things that are coincidentally and incorrectly safe because of the GIL are suddenly problems. – tadman Dec 13 '12 at 16:57