an extremely naive question regarding synchronized...

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 14 14:40:54 PST 2016


On 11/14/16 12:43 PM, 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.

It's expensive when compared to simply reading a piece of memory.

synchronized means that the CPU core has to sync it's view of memory 
with the memory manager and all the other CPUs in the system.

> And the graph shows 1B get() calls.  I assume B stands for billion.
> What use case would require so many gets?

This is a typical technique with benchmarking to show some measurable 
results. If it had, say 10 gets, the noise of context switching, or of 
different various things running in the OS could sway the graph a huge 
amount. Not to mention that time measurement on an OS is in discrete 
units that may not even capture the short time to do 10 gets.

In other words, if your stopwatch only has a second hand, and it takes 1 
ms to do something, you need to repeat that thing 10,000 times in order 
to properly measure it.

-Steve


More information about the Digitalmars-d-learn mailing list