On Tue July 29 2003 3:50 am, Yukihiro Matsumoto wrote:
> |w1 = Worker1.new
> |w1.doStuff
> |
> |w2 = Worker2.new
> |w2.doStuff
> |w2.showResult
>
> I don't know what you meant.  If w1 is referenced from somewhere, w1
> will not be garbage-collected.

Sorry I wasn't more clear.  I meant to give a case where there are no more 
references to w1 after the doStuff method is called.  It's not w1 or w2 being 
garbage-collected that I'm worried about, it's the "@stats" variable that 
they both use, which is a singleton instance.

What I'd like is a way to make sure that the instance variable of a singleton 
object I create in the first class still exists by the time the second class 
tries to create it.
 
class Worker1
   def doStuff
     @stats = Stats.instance # The instance of the stats singleton is created
     ...
   end
end

class Worker2
   def doOtherStuff
     @stats = Stats.instance # It still exists here
     ...
   end

   def showResult
     @stats.dumpStats
   end
end

Worker1.new.doStuff

# Here is where I don't want the stats singleton to be GC'd

w = Worker2.new
w.doOtherStuff
w.showResult

I guess what I'm looking for is a way to create a hidden global variable when 
a singleton instance is created, in a way that there is no danger of name 
clashes.  Because there would always be at least one reference to the 
singleton, it would only get GC'd at the end of the program's lifetime, and 
this would guarantee it would only ever be created once.

Some examples of where this would be useful:
* There are a large number of unrelated classes which should dump debugging 
info into a log.  You want a new log each time the program is run, and you 
want to replace the old log.  So you create / truncate the file when the 
first class needs to log something, and each other class appends to the log, 
until the end of the program.
* The act of creating an instance of a class is long and time-consuming, so 
you only want it to happen once for the entire lifetime of the program, 
whether it's used frequently or not

I hope I explained it better this time.

Ben