# Thread specific singleton's

**URL:** <https://www.ruby-forum.com/t/thread-specific-singletons/72211>\
**Category:** Ruby\
**Created:** [December 19, 2005, 8:12am UTC](https://www.ruby-forum.com/t/thread-specific-singletons/72211 "2005-12-19T08:12:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![lstrecv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e68b1a/32.png) [@lstrecv](https://www.ruby-forum.com/u/lstrecv)\
**Post date:** [December 19, 2005, 8:12am UTC](https://www.ruby-forum.com/t/thread-specific-singletons/72211/1 "2005-12-19T08:12:36Z")

</div>

How do I make a thread specific Singleton?

That is, once instance per thread.

Related question: why do Singleton’s use the Name.instance.method idiom  
(using instance methods) as opposed to Name.method (using class  
methods), which seems simpler and clearer.

---

<div class="post-metadata">

**Author:** ![lstrecv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e68b1a/32.png) [@lstrecv](https://www.ruby-forum.com/u/lstrecv)\
**Post date:** [December 19, 2005, 9:55am UTC](https://www.ruby-forum.com/t/thread-specific-singletons/72211/2 "2005-12-19T09:55:36Z")

</div>

List R. wrote:

> How do I make a thread specific Singleton?
> 
> That is, once instance per thread.

Thread.current[:my\_singleton\_id] ||= whatever\_creation\_expression

> Related question: why do Singleton’s use the Name.instance.method  
> idiom (using instance methods) as opposed to Name.method (using class  
> methods), which seems simpler and clearer.

It’s the typical way the singleton pattern works. Not all PL have  
Ruby’s  
flexibility with methods on class instances. Also you can still inherit  
the class and have derived classes that do not use singleton pattern but  
can still use super class methods. I probably missed something else.

Kind regards

```
robert
```

---

<div class="post-metadata">

**Author:** ![lstrecv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e68b1a/32.png) [@lstrecv](https://www.ruby-forum.com/u/lstrecv)\
**Post date:** [December 19, 2005, 10:04am UTC](https://www.ruby-forum.com/t/thread-specific-singletons/72211/3 "2005-12-19T10:04:37Z")

</div>

On Dec 19, 2005, at 2:12 AM, List R. wrote:

> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

def thread\_singleton()  
Thread.current[“my singleton”] ||= MyOnePerThreadClass.new #  
note, don’t actually make MyOnePerThreadClass a “real” singleton  
end

Then whenever you want to use the thread singleton in a given thread  
use the thread\_singleton function

e.g.:

Thread.start do  
thread\_singleton.send\_some\_message  
end

Thread.start do  
thread\_singleton.send\_other\_message # a different singleton  
for this thread than the other thread, but will be the same for the  
duration of this thread  
end

etc.

As far as your Name.method question, there’s no particular reason not  
to… If you want you can implement a singleton like that.
