Module: Knj::Threadsafe::Monitored

Included in:
Synced_array, Synced_hash
Defined in:
lib/knj/threadsafe.rb

Overview

This module can be included on a class to make all method-calls synchronized (by using monitor). Examples with array and hash are below.

Examples

class MySyncedClass < SomeOtherClassThatNeedsToBeSynchronized

include Knj::Threadsafe::Monitored

end

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/knj/threadsafe.rb', line 48

def self.included(base)
  Knj::Strings.const_get_full(base.to_s).class_eval do
    self.instance_methods.each do |method_name|
      #These two methods create warnings under JRuby.
      if RUBY_ENGINE == "jruby"
        next if method_name == :instance_exec or method_name == :instance_eval
      end
      
      new_method_name = "_ts_#{method_name}"
      alias_method(new_method_name, method_name)
      
      define_method method_name do |*args, &block|
        #Need to use monitor, since the internal calls might have to run not-synchronized, and we have just overwritten the internal methods.
        @_ts_mutex = Monitor.new if !@_ts_mutex
        @_ts_mutex.synchronize do
          return self._ts___send__(new_method_name, *args, &block)
        end
      end
    end
  end
end