Question on thread safety and caching!

Question on thread safety and caching!

I’m very curious if there are any opinions on the best way, patterns to use an in-memory cache, using a constant rather than class @@var or class instance variables.

Here’s what I’m thinking:

class SomeKeyToValueCache
  # rubocop:disable Style/MutableConstant
  SOME_KEY_TO_VALUE = {}
  # rubocop:enable Style/MutableConstant
  MUTEX = Mutex.new

  def self.value_for_some_key(key)
    return SOME_KEY_TO_VALUE[key] if SOME_KEY_TO_VALUE.present?

    init_hashes
    SOME_KEY_TO_VALUE[key]
  end

  def self.init_hashes
    return if SOME_KEY_TO_VALUE.present?

    MUTEX.synchronize do
      next if SOME_KEY_TO_VALUE.present?

      SOME_KEY_TO_VALUE.merge!(
        MY_MODEL.select(:key, :value).pluck(:alias, :name).to_h,
      ).deep_freeze
    end
  end
end
  1. Any thread safety issues with ^^^ on Ruby MRI?
  2. Good to use a constant rather than @@var or a class instance var?
  3. Good to lazy ready the DB table?