Not sure if threads safety even applies to ||=
.
Was originally reading about ActiveSupport::Memoizable and wondered about thread safety there.
This great post on thread safety concepts in Ruby by Luca Guidi shows that ||=
is not thread-safe (at least in MRI).
It depends on the implementation. Be aware that x ||= y
expands to x || x = y
, and that x = y
is only executed if x
is either false
or nil
.
With that said, the C implementation of the Ruby language should be completely thread safe.
YARV uses native threads in order to implement concurrency, which do run in true parallel. However, in order to maintain backward compatibility, a global, interpreter-wide lock was introduced.
JRuby, however, imposes no internal locking on your code, so you must manually synchronize your calls when needed.
See another answer I've given about the subject for more details. Also, read this excellent answer by Jörg W Mittag for a more in-depth look at the threading models of the various Ruby implementations.