an extremely naive question regarding synchronized...

Kapps via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Nov 15 12:05:13 PST 2016


On Monday, 14 November 2016 at 17:43:37 UTC, WhatMeWorry wrote:
>
> I was reading this fasciniating article:
>
> https://davesdprogramming.wordpress.com/2013/05/06/low-lock-singletons/
>
> And to quote a section of it:
> -----------------------------------------------------
> static MySingleton get() {
>     synchronized {
>       if (instance_ is null) {
>         instance_ = new MySingleton;
>       }
>     }
>     return instance_;
>   }
>
> Now, if Thread 1 calls get(), it has a chance to finish 
> instantiating instance_ and storing a reference to it before 
> Thread 2 checks whether instance_ is null.  There’s only one 
> problem with this:  It comes at a huge performance cost 
> (benchmarks forthcoming).  Entering a synchronized block is 
> expensive.
> -----------------------------------------------------
>
> Why is the synchronized block so expensive?  Isn't it just 
> doing one conditional and a new command?  Again, to my naive 
> way of thinking, this seems like a very small blocking window.
>
> And the graph shows 1B get() calls.  I assume B stands for 
> billion.  What use case would require so many gets?
>
> Thanks.

Keep in mind, this is only slow for such a large amount of calls.
If you're calling this only a hundred times a second, then who 
cares if it's slower. After all, with GDC we were looking at 1 
billion calls in 21 seconds. That's 47,000 calls per 
*millisecond*.


More information about the Digitalmars-d-learn mailing list