MonitorMixin woes

October 28, 2011

MonitorMixin is pretty awesome, it allows you to safely perform operations that can be thread-unsafe any class can be MonitorMixin enabled quite easily.

class MyClass

  include MonitorMixin

  def add_item(name, item)
    @list[name] = item
  end

  def remove_item(name)
    @list.delete name
  end
end

That was half of the story, now to really protect your potentially unsafe operations you need to guard them inside a syncronize block: That is it, now you can turn your potentially unsafe operations into safer ones by doing:

class MyClass

  include MonitorMixin

  def add_item(name, item)
     syncronize do
      @list[name] = item
     end
  end

  def remove_item(name)
     syncronize do
      @list.delete name
    end
  end
end

Problem arises when you try to override initialize

class MyClass

  include MonitorMixin

  def initialize
    do_something_awesome
  end

  def add_item(name, item)
     syncronize do
      @list[name] = item
     end
  end

  def remove_item(name)
     syncronize do
      @list.delete name
    end
  end
end

If we used this code we would get an error about initialize having the wrong number of arguments, looking in google i ve found that i need to call super() inside my initialize method, this should be fairly obvious but make sure to use super() not super, or it wont work and i am not sure why

$ `initialize': wrong number of arguments

I am asking my self why this happens if i didnt subclass MonitorMixin, i only included it, for all i know MyClass is not a subclass of MonitorMixin, i think i will read back about the ruby object model and maybe peek a bit inside MonitorMixin to see why it is working this way

Finally here is a version that works

class MyClass

  include MonitorMixin

  def initialize
    do_something_awesome
    super()
  end

  def add_item(name, item)
     syncronize do
      @list[name] = item
     end
  end

  def remove_item(name)
     syncronize do
      @list.delete name
    end
  end
end

Comments

comments powered by Disqus