Class: Concurrent::CopyOnWriteObserverSet

Inherits:
Object
  • Object
show all
Defined in:
lib/concurrent/copy_on_write_observer_set.rb

Overview

A thread safe observer set implemented using copy-on-write approach: every time an observer is added or removed the whole internal data structure is duplicated and replaced with a new one.

Instance Method Summary collapse

Constructor Details

#initializeCopyOnWriteObserverSet

Returns a new instance of CopyOnWriteObserverSet.



8
9
10
11
# File 'lib/concurrent/copy_on_write_observer_set.rb', line 8

def initialize
  @mutex = Mutex.new
  @observers = {}
end

Instance Method Details

#add_observer(observer, func = :update) ⇒ Symbol

Adds an observer to this set

Parameters:

  • observer (Object)

    the observer to add

  • func (Symbol) (defaults to: :update)

    the function to call on the observer during notification. Default is :update

Returns:

  • (Symbol)

    the added function



17
18
19
20
21
22
23
24
# File 'lib/concurrent/copy_on_write_observer_set.rb', line 17

def add_observer(observer, func=:update)
  @mutex.synchronize do
    new_observers = @observers.dup
    new_observers[observer] = func
    @observers = new_observers
  end
  func
end

#count_observersInteger

Returns the observers count.

Returns:

  • (Integer)

    the observers count



46
47
48
# File 'lib/concurrent/copy_on_write_observer_set.rb', line 46

def count_observers
  observers.count
end

#delete_observer(observer) ⇒ Object

Returns the deleted observer.

Parameters:

  • observer (Object)

    the observer to remove

Returns:

  • (Object)

    the deleted observer



28
29
30
31
32
33
34
35
# File 'lib/concurrent/copy_on_write_observer_set.rb', line 28

def delete_observer(observer)
  @mutex.synchronize do
    new_observers = @observers.dup
    new_observers.delete(observer)
    @observers = new_observers
  end
  observer
end

#delete_observersCopyOnWriteObserverSet

Deletes all observers

Returns:



39
40
41
42
# File 'lib/concurrent/copy_on_write_observer_set.rb', line 39

def delete_observers
  self.observers = {}
  self
end

#notify_and_delete_observers(*args, &block) ⇒ CopyOnWriteObserverSet

Notifies all registered observers with optional args and deletes them.

Parameters:

  • args (Object)

    arguments to be passed to each observer

Returns:



62
63
64
65
66
# File 'lib/concurrent/copy_on_write_observer_set.rb', line 62

def notify_and_delete_observers(*args, &block)
  old = clear_observers_and_return_old
  notify_to(old, *args, &block)
  self
end

#notify_observers(*args, &block) ⇒ CopyOnWriteObserverSet

Notifies all registered observers with optional args

Parameters:

  • args (Object)

    arguments to be passed to each observer

Returns:



53
54
55
56
# File 'lib/concurrent/copy_on_write_observer_set.rb', line 53

def notify_observers(*args, &block)
  notify_to(observers, *args, &block)
  self
end