[concurrency-interest] Is this a pattern or an anti-pattern for check-and-act?

Arno Haase arno.haase at haase-consulting.com
Mon Feb 29 15:06:10 EST 2016


Yes, it works, i.e. it ensures thread-safe lazy initialization - if the
doubly checked variable is volatile, as pointed out by Christian.

Regarding 'scaling', I am not sure what you mean, Nader. Your original
code snippet initializes a static variable, i.e. a singleton - what do
you mean by scaling singleton initialization?

While there are valid use cases for lazy initialization (e.g. Scala's
'lazy val'), if performance and scaling is a priority, there is a
variety of ways to safely publish state changes. For some problems,
there are solutions that do not incur the overhead of even a volatile
read on every access.

If you explain the problem you are trying to solve, we could discuss
alternative approaches.

- Arno


Am 29.02.2016 um 20:37 schrieb Christian Schudt:
> Hi,
> 
> foo should be volatile. Why is explained in the following link.
> 
> You want to read into „Double-Checked Locking“:
> https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
> 
> It also recommends to copy foo to a local variable to save expensive reads on the volatile variable, "which can improve the method's overall performance by as much as 25 percent“.
> 
> This seems to be the best version:
> 
> class Foo {
>     private volatile Helper helper;
>     public Helper getHelper() {
>         Helper result = helper;
>         if (result == null) {
>             synchronized(this) {
>                 result = helper;
>                 if (result == null) {
>                     helper = result = new Helper();
>                 }
>             }
>         }
>         return result;
>     }
> }
> 
> 
> — Christian
> 
> 
>> Am 29.02.2016 um 20:17 schrieb Nader Aeinehchi <nader at aeinehchi.com>:
>>
>> Hello
>>
>> I saw this pattern on an open source project, and wonder if it is thread safe?  If so, would it scale?
>>
>>     private final static Object lock = new Object();
>>
>>     private static Foo foo;
>>
>>     public static Foo getInstance(){
>>
>>         if(foo == null){
>>             synchronized (lock){
>>                 if(foo == null){
>>                     foo = new Foo();
>>                 }
>>             }
>>         }
>>
>>         return foo;
>>     }
>>
>> In advance, thank you very much
>>
>> Nader
>> _______________________________________________
>> Concurrency-interest mailing list
>> Concurrency-interest at cs.oswego.edu
>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
> 
> 
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
> 


More information about the Concurrency-interest mailing list