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

Christian Schudt christian.schudt at gmx.de
Mon Feb 29 14:37:38 EST 2016


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




More information about the Concurrency-interest mailing list