Class: SynchronizedDelegator
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- SynchronizedDelegator
- Defined in:
- lib/thread_safe/synchronized_delegator.rb
Overview
This class provides a trivial way to synchronize all calls to a given object
by wrapping it with a Delegator
that performs Monitor#enter/exit
calls
around the delegated #send
. Example:
array = [] # not thread-safe on many impls array = SynchronizedDelegator.new([]) # thread-safe
A simple Monitor
provides a very coarse-grained way to synchronize a given
object, in that it will cause synchronization for methods that have no need
for it, but this is a trivial way to get thread-safety where none may exist
currently on some implementations.
This class is currently being considered for inclusion into stdlib, via https://bugs.ruby-lang.org/issues/8556
Instance Method Summary collapse
-
#initialize(obj) ⇒ SynchronizedDelegator
constructor
A new instance of SynchronizedDelegator.
- #method_missing(method, *args, &block) ⇒ Object
- #setup ⇒ Object
- #teardown ⇒ Object
Constructor Details
#initialize(obj) ⇒ SynchronizedDelegator
Returns a new instance of SynchronizedDelegator.
28 29 30 31 |
# File 'lib/thread_safe/synchronized_delegator.rb', line 28 def initialize(obj) __setobj__(obj) @monitor = Monitor.new end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
33 34 35 36 37 38 39 40 41 |
# File 'lib/thread_safe/synchronized_delegator.rb', line 33 def method_missing(method, *args, &block) monitor = @monitor begin monitor.enter super ensure monitor.exit end end |
Instance Method Details
#setup ⇒ Object
19 20 21 22 |
# File 'lib/thread_safe/synchronized_delegator.rb', line 19 def setup @old_abort = Thread.abort_on_exception Thread.abort_on_exception = true end |
#teardown ⇒ Object
24 25 26 |
# File 'lib/thread_safe/synchronized_delegator.rb', line 24 def teardown Thread.abort_on_exception = @old_abort end |