Instance variables in background worker


I was told that doing something like for a background worker code this is bad

class Greetings
  def self.perform(num, first, second)
    @num = num
    @first = first
    @second = second


  def self.say_first
    puts "#{@num} #{@first}"

  def self.say_second
    puts "#{@num} #{@second}"

We can’t be certain of the instance variables during the execution. It could be changed or it might still have the previous value.

If this is true how can I reproduce this or test this?

Or maybe I was told wrong?


Your instance variables are actually “class instance variables”, since they’re referenced inside class methods rather than instance methods. As a result, they aren’t thread-safe. If you have multiple threads accessing the Greeting class at the same time, the “class instance variables” are shared, so each thread could step on the other thread’s toes.

Usually you can find a way to refactor class methods so they don’t need “class instance variables”.

There are at least a couple of ways to do this:

  1. Don’t use class methods — instead, use instance methods on a class that is actually instantiated (and therefore has its own thread-safe instance variables)
  2. Pass arguments directly to the class methods, rather than passing data via class instance variables