Why is the volatile field copied to a local variable when doing double check locking

前端 未结 2 1482
庸人自扰
庸人自扰 2021-02-06 14:02

I am reading about double check locking from Effective Java. The code does the following:

private volatile FieldType field;  
FieldType getField(         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 14:30

    The thinking in that example is that result/field will be used more than once further down I guess. Accessing result is cheaper (it's not volatile).

    You have a second volatile read when doing the return otherwise.

    Use the initializaton on demand holder pattern instead if you need to do this. http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

    Adding some of my clarifications in the comments to the answer itself for well... clarity:

    Short version: A local variable can just be in a register in (one of) the cpu(s) (and in one of the cpu's cores if multiple etc). That's as fast as it gets. A volatile variable must be checked for changes in other cores/caches/cpus/memory, but the details can be very hardware specific (cache lines, memory barriers etc). But also jvm specific, (the hotspot server compiler might hoist non volatile variables for example) and it imposes limits on reordering instructions for possible performance gains as well

提交回复
热议问题