Search code examples
ruby-on-railsrubyconcurrent-ruby

Thread safe counter inside a method


I saw some retry code written like this, it tries to call a service 3 times if some exception is raised, Im trying to understand in a non-MRI multi-threaded server, is this counter thread safe? is it necessary to lock the process using Mutex?

This is how its been called

MyClass.new.my_method

class MyClass
  def my_method
    counter = 3
    begin
      call_some_service_raise_some_exception
    rescue SomeException => e
      retry if counter.positive?
    end
  end
end

Solution

  • Assuming the variable counter is scoped to that method only, and that there is no funny shenanigans going on with Singleton or any other weird stuff, then yes, that method should be thread safe in its current form.

    If, however, counter is an instance variable and you are using an accessor to set it, then that method is not thread safe. You may never encounter the race condition if you're using every MyClass once only, but all it takes is one well-meaning refactoring to reuse MyClass and suddenly you've got a race condition there.

    Basically - if your method is self-contained, uses variables scoped to it only, and references no external shared data then it is thread safe by default.

    As soon as you use something that could be accessed at the same time by another thread, you have a potential race condition in the making and you should start thinking about synchronising access to the shared resources.