Wait until a Singleton instantiated?


#1

Hi,
I have singleton class I want to observe with another class. The
problem is that the singleton class will create the instance of the
class that wants to observe it.
Here is an example:
require ‘singleton’
require ‘observer’

class A
include Singleton
include Observable

def initialize
B.new
sleep 10
end
end

class B
def initialize
# register for A updates
A.instance.add_observer(self) # will fail, because it waits for A
end
end

A.instance

You need to stop the program with Control-C and you get:

^C/usr/lib/ruby/1.8/singleton.rb:149:in sleep': Interrupt from /usr/lib/ruby/1.8/singleton.rb:149:in_instantiate?’
from /usr/lib/ruby/1.8/singleton.rb:105:in instance' from c.rb:21:ininitialize’
from c.rb:10:in new' from c.rb:10:ininitialize’
from /usr/lib/ruby/1.8/singleton.rb:94:in new' from /usr/lib/ruby/1.8/singleton.rb:94:ininstance’
from c.rb:25

Command terminated

The problem is that A didn’t finish initializing, and B in order to
add_observer waits for A to finish initialize. So both A and B
sleeping waiting for each other.

I thought to solve it by creating a thread that will wait for A to
finish initialize.
Something like this:
Thread.new(self) do |me|
while A.instance.not_initialize? do
sleep 2
end
A.instance.add_observer(self)
end

But how do I monitor if A finished initialize?
Also, is there a better way of doing this? Idiom?

Thanks,
Kfir


#2

On Sat, May 9, 2009 at 1:20 PM, Kfir L. removed_email_address@domain.invalid wrote:

include Observable

def initialize
B.new
sleep 10
end
end

Why are you instantiating B here? This is odd for several reasons:

  1. The whole point of the observer pattern is that the observable
    object doesn’t shouldn’t know about the actual observers or who
    created them.

  2. Your initialize method creates an instance of B and then ignores
    it, it’s subject to be GCed since there are no references to it.

So why not:

class A
include Singleton
include Observable

def initialize
sleep 10
end
end

class B
def initialize
A.instance.add_observer(self)
end
end

a_observer = B.new


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale