Llamarada

Tomar de la élite lo que pertenece a todos

MonitorMixin Woes

| Comments

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

adding MonitorMixin to any class is easy
1
2
3
4
5
6
7
8
9
10
11
12
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:

thread proofing your methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

be careful when overriding initialize in a class that uses MonitorMixin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

oops
1
$ `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

Final version
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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