Not sure if threads safety even applies to ||=
.
Was originally reading about ActiveSupport::Memoizable and wondered about thread safety there.
Unfortunately, Ruby doesn't ship with any thread-safe Array or Hash implementations. The core Array and Hash classes are not thread-safe by default, nor should they be.
Yes, but even though only one thread runs at a time that doesn't make multi-threaded Ruby code thread-safe as what should be atomic operations can span multiple statements.
Keep it in memory thread_mattr_accessor method which makes it easy to build a trivial thread-safe cache service. Rails' implementation ensures every thread has its own storage location for cached_value ; therefore this should be thread-safe (assuming #compute_value can safely run both concurrently and in parallel).
Rails as a framework is thread-safe. So, the answer is yes! The second link that you posted here names many of the Rails servers that don't do well with multi-threading. He later mentions that nginx is the way to go (it is definitely the most popular one and highly recommended).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With