sent-hil sent-hil - 3 months ago 9
Ruby Question

Is ||= in Ruby thread safe?

Not sure if threads safety even applies to

||=
.

Was originally reading about ActiveSupport::Memoizable and wondered about thread safety there.

Answer

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 neither false nor 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.

Comments