Is this a pattern or an anti-pattern for check-and-act?

classic Classic list List threaded Threaded
28 messages Options
12
Reply | Threaded
Open this post in threaded view
|

Is this a pattern or an anti-pattern for check-and-act?

nader
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
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

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 <[hidden email]>:
>
> 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
> [hidden email]
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Arno Haase
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 <[hidden email]>:
>>
>> 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
>> [hidden email]
>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>
> _______________________________________________
> Concurrency-interest mailing list
> [hidden email]
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Aleksey Shipilev-2
In reply to this post by nader
On 02/29/2016 10:17 PM, Nader Aeinehchi wrote:
> I saw this pattern on an open source project, and wonder if it is thread
> safe?  If so, would it scale?

See:
 http://shipilev.net/blog/2014/safe-public-construction/

-Aleksey


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest

signature.asc (853 bytes) Download Attachment
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

nader
Hello everyone

Thank you very much for the good comments.

As stated earlier, I found this pattern on an open source project.  For the courtesy, I "intentionally" made the code anonymous (called it Foo).  

Firstly, The original code contains "static" modifier.  The example that Christian provided, contains no static modifier.  Would it still be orthogonal to add volatile to a static instance variable, in this case?

Secondly, given that code does not have a volatile modifier, is it still thread safe? [I have my doubts, therefore I ask]

Thirdly, suppose Foo is a singleton which is asked by almost every single call to a server.  Would this code have good performance (with/without "volatile" modifier)?

In advance, thank you very much

Best regards
Nader

On Mon, Feb 29, 2016 at 9:31 PM, Aleksey Shipilev <[hidden email]> wrote:
On 02/29/2016 10:17 PM, Nader Aeinehchi wrote:
> I saw this pattern on an open source project, and wonder if it is thread
> safe?  If so, would it scale?

See:
 http://shipilev.net/blog/2014/safe-public-construction/

-Aleksey



_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Michael Kuhlmann
Hi Nader!> Firstly, The original code contains "static" modifier.  The
example that
> Christian provided, contains no static modifier.  Would it still be
> orthogonal to add volatile to a static instance variable, in this case?

Yes, that will work as well.

> Secondly, given that code does not have a volatile modifier, is it still
> thread safe? [I have my doubts, therefore I ask]

It will be thread safe if Foo is immutable, or more precise, if it
itself has at least one instance variable that is declared as final.

Otherwise, it won't be thread safe without the volatile modifier.

> Thirdly, suppose Foo is a singleton which is asked by almost every
> single call to a server.  Would this code have good performance
> (with/without "volatile" modifier)?

In general, most often you can avoid double checked patterns completely.

When Foo is asked so often anyway, what benefit will you gain from the
lazy initialization then? Nothing.

Double checked locking is only useful when Foo itself is heavy-weight,
or the creation cost is high, and if it's not unlikely that it will
probably never be used. Then you can avoid that cost in some cases, and
when it's necessary, it will be there.

In other cases, esp. when it's used anyway, you better run with a
singleton in a constant field.

But even if you want to load lazily, there's a better and fast approach.
Use a holder class for it like this:

public class Foo {
    private static class Holder {
        static final Foo INSTANCE = new Foo();
    }

    public static Foo getInstance() {
        return Holder.INSTANCE;
    }
    ....
}


Then the class loader will be used to instantiate Foo lazily because the
holder class will only be initialized on the first call to
getInstance(), but all subsequent calls will work directly on the
constant which is the fastest access method anyway.

Best,
Michael

_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Arno Haase
In reply to this post by nader
> Firstly, The original code contains "static" modifier.  The example that
> Christian provided, contains no static modifier.  Would it still be
> orthogonal to add volatile to a static instance variable, in this case?

The two are entirely independent.

> Secondly, given that code does not have a volatile modifier, is it still
> thread safe? [I have my doubts, therefore I ask]

No, it is not, in the sense that it does not conform to the Java Memory
Model.

> Thirdly, suppose Foo is a singleton which is asked by almost every
> single call to a server.  Would this code have good performance
> (with/without "volatile" modifier)?

The correct version (with volatile) adds the overhead of a volatile read
for every access. That may or may not be a noticeable overhead,
depending on your use case. If you want to avoid that, there are
alternatives, see the links posted by Christian and Aleksey.

- Arno
_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Millies, Sebastian
In reply to this post by Michael Kuhlmann
Especially if Foo is heavyweight, using the holder pattern has the drawback that you'll never get rid of the object. Also, the holder pattern is not as amenable for passing in a supplier. It really depends on your use case. When I need a static singleton, I usually find myself using an Enum (something that is not discussed by Aleksey, I wonder why not, as it is also a form of safe publication), otherwise I tend to use double checked locking with a local variable. Generally, I try to avoid the need for either.

-- Sebastian

-----Original Message-----
From: [hidden email] [mailto:[hidden email]] On Behalf Of Michael Kuhlmann
Sent: Tuesday, March 01, 2016 9:57 AM
To: [hidden email]
Subject: Re: [concurrency-interest] Is this a pattern or an anti-pattern for check-and-act?
[snip]

Double checked locking is only useful when Foo itself is heavy-weight, or the creation cost is high, and if it's not unlikely that it will probably never be used. Then you can avoid that cost in some cases, and when it's necessary, it will be there.

In other cases, esp. when it's used anyway, you better run with a singleton in a constant field.

But even if you want to load lazily, there's a better and fast approach.
Use a holder class for it like this:

public class Foo {
    private static class Holder {
        static final Foo INSTANCE = new Foo();
    }

    public static Foo getInstance() {
        return Holder.INSTANCE;
    }
    ....
}


Then the class loader will be used to instantiate Foo lazily because the holder class will only be initialized on the first call to getInstance(), but all subsequent calls will work directly on the constant which is the fastest access method anyway.

Best,
Michael

_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest

Software AG – Sitz/Registered office: Uhlandstraße 12, 64297 Darmstadt, Germany – Registergericht/Commercial register: Darmstadt HRB 1562 - Vorstand/Management Board: Karl-Heinz Streibich (Vorsitzender/Chairman), Eric Duffaut, Dr. Wolfram Jost, Arnd Zinnhardt; - Aufsichtsratsvorsitzender/Chairman of the Supervisory Board: Dr. Andreas Bereczky - http://www.softwareag.com


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

nader
In reply to this post by Michael Kuhlmann
Thank you very much for the good response Michael.

In the original author's code, the Foo class is not immutable.  There is no "volatile" modifier.  Therefore, we can draw the conclusion that the code is not thread safe.  As such patterns often appear in code, perhaps it should be marked as "antipattern"?

Personally, I never use double checked locking as it complicates things...  

In general, my impression is that people exaggerate the cost of object initialization.  Therefore, they often go for lazy initialization.  In particular in singletons upon an application's or server's  startup, there is often no reason to write lazy initialization whereas there is a huge penalty for writing not-thread-safe code.

I like the Holder pattern, as in Concurrency in Practice book, that you propose.  

All in all thanks a lot for good comments on this topic.  

On Tue, Mar 1, 2016 at 9:56 AM, Michael Kuhlmann <[hidden email]> wrote:
Hi Nader!> Firstly, The original code contains "static" modifier.  The
example that
> Christian provided, contains no static modifier.  Would it still be
> orthogonal to add volatile to a static instance variable, in this case?

Yes, that will work as well.

> Secondly, given that code does not have a volatile modifier, is it still
> thread safe? [I have my doubts, therefore I ask]

It will be thread safe if Foo is immutable, or more precise, if it
itself has at least one instance variable that is declared as final.

Otherwise, it won't be thread safe without the volatile modifier.

> Thirdly, suppose Foo is a singleton which is asked by almost every
> single call to a server.  Would this code have good performance
> (with/without "volatile" modifier)?

In general, most often you can avoid double checked patterns completely.

When Foo is asked so often anyway, what benefit will you gain from the
lazy initialization then? Nothing.

Double checked locking is only useful when Foo itself is heavy-weight,
or the creation cost is high, and if it's not unlikely that it will
probably never be used. Then you can avoid that cost in some cases, and
when it's necessary, it will be there.

In other cases, esp. when it's used anyway, you better run with a
singleton in a constant field.

But even if you want to load lazily, there's a better and fast approach.
Use a holder class for it like this:

public class Foo {
    private static class Holder {
        static final Foo INSTANCE = new Foo();
    }

    public static Foo getInstance() {
        return Holder.INSTANCE;
    }
    ....
}


Then the class loader will be used to instantiate Foo lazily because the
holder class will only be initialized on the first call to
getInstance(), but all subsequent calls will work directly on the
constant which is the fastest access method anyway.

Best,
Michael

_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

nader
In reply to this post by Arno Haase
Thank you Arno for confirming that this class -as it stands - is not thread safe.

On Tue, Mar 1, 2016 at 10:05 AM, Arno Haase <[hidden email]> wrote:
> Firstly, The original code contains "static" modifier.  The example that
> Christian provided, contains no static modifier.  Would it still be
> orthogonal to add volatile to a static instance variable, in this case?

The two are entirely independent.

> Secondly, given that code does not have a volatile modifier, is it still
> thread safe? [I have my doubts, therefore I ask]

No, it is not, in the sense that it does not conform to the Java Memory
Model.

> Thirdly, suppose Foo is a singleton which is asked by almost every
> single call to a server.  Would this code have good performance
> (with/without "volatile" modifier)?

The correct version (with volatile) adds the overhead of a volatile read
for every access. That may or may not be a noticeable overhead,
depending on your use case. If you want to avoid that, there are
alternatives, see the links posted by Christian and Aleksey.

- Arno
_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Michael Kuhlmann
In reply to this post by nader
Am 01.03.2016 um 11:38 schrieb Nader Aeinehchi:
> Thank you very much for the good response Michael.
>
> In the original author's code, the Foo class is not immutable.  There is
> no "volatile" modifier.  Therefore, we can draw the conclusion that the
> code is not thread safe.  As such patterns often appear in code, perhaps
> it should be marked as "antipattern"?

Yes, at least I would say so.

Misunderstanding the complexity of the double checked pattern is a
common mistake. I remember that in my former company, we used that
pattern a lot; the people already knew that it was broken, but nobody
fixed it. The problem is that as long as it works, nobody will complain.
And it most often works.

BTW, it was *always* broken in versions before Java5 - even with the
volatile modifier.

And I totally agree that in most cases, the cost of object
initialization is insignificant.

Best,
Michael
_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Andrew Haley
On 03/01/2016 11:11 AM, Michael Kuhlmann wrote:
> Am 01.03.2016 um 11:38 schrieb Nader Aeinehchi:
>> > Thank you very much for the good response Michael.
>> >
>> > In the original author's code, the Foo class is not immutable.  There is
>> > no "volatile" modifier.  Therefore, we can draw the conclusion that the
>> > code is not thread safe.  As such patterns often appear in code, perhaps
>> > it should be marked as "antipattern"?
<
> Yes, at least I would say so.

And this antipattern has even got a name: "Broken double-checked
locking."

Andrew.

_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

nader
+1

On Tue, Mar 1, 2016 at 2:59 PM, Andrew Haley <[hidden email]> wrote:
On 03/01/2016 11:11 AM, Michael Kuhlmann wrote:
> Am 01.03.2016 um 11:38 schrieb Nader Aeinehchi:
>> > Thank you very much for the good response Michael.
>> >
>> > In the original author's code, the Foo class is not immutable.  There is
>> > no "volatile" modifier.  Therefore, we can draw the conclusion that the
>> > code is not thread safe.  As such patterns often appear in code, perhaps
>> > it should be marked as "antipattern"?
<
> Yes, at least I would say so.

And this antipattern has even got a name: "Broken double-checked
locking."

Andrew.

_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Jeff Hain
In reply to this post by nader
Hi.



>When Foo is asked so often anyway, what benefit will you gain from the
>lazy initialization then? Nothing.
>
>Double checked locking is only useful when Foo itself is heavy-weight,
>or the creation cost is high, and if it's not unlikely that it will
>probably never be used. Then you can avoid that cost in some cases, and
>when it's necessary, it will be there.



In some cases the Foo instance to use is only known after some point,
so you need some laziness.

What I would do then is use the holder pattern, and throw if the instance
is not yet known at the time it's loaded.



But in my book Singletons are mostly an anti-pattern, and if possible
I would try to avoid them completely, and have nothing that is both
static and mutable, especially when dealing with concurrency.

Not giving an exhaustive list of reason why here
(if you want some you can start there:
 https://www.michaelsafyan.com/tech/design/patterns/singleton),
but just a personal example:
On some project I used a dummy instance of my app in background
for JIT warm-up, so that the "real" one would start quickly when
needed (and possibly while the dummy one was still running).
With even just one singleton that would not have been possible.



-Jeff


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Peter
In reply to this post by nader
 There's an example of unsafe publication in java.security.Permissions, on occassion this class cannot resolve UnresolvedPermission, because the field hasUnresolved on line 96 is accessed under race conditions.

This class was written as a work around:

https://github.com/pfirmstone/river-internet/blob/trunk/src/org/apache/river/api/security/ConcurrentPermissions.java

There's a number of similar bugs in the  security infrastructure, most are masked by external synchronization.

We have our own policy provider that works around 95% of these issues by thread confining all PermissionCollection instances.

The policy provider relies on final fields for safe publication of Permission instances (after lazy initialisers are deliberately invoked).

PermissionCollection instances are created and discarded within method local scope.

CPU consumption of this policy provider is about 0.1% and is highly scalable in comparison the standard policy provider that consumes 10% cpu and limits scalability of applications.

https://github.com/pfirmstone/river-internet/blob/trunk/src/org/apache/river/api/security/ConcurrentPolicyFile.java

I can donate the policy provider and some required classes under the gpl, but cannot donate the policy file parser as it includes AL2 code written by others.  I've signed a contributor agreement.

Regards,

Peter.


Sent from my Samsung device.
 
---- Original message ----
From: Aleksey Shipilev <[hidden email]>
Sent: 01/03/2016 06:31:24 am
To: Nader Aeinehchi <[hidden email]>; concurrency-interest <[hidden email]>
Subject: Re: [concurrency-interest] Is this a pattern or an anti-pattern for check-and-act?

On 02/29/2016 10:17 PM, Nader Aeinehchi wrote:
> I saw this pattern on an open source project, and wonder if it is thread
> safe?  If so, would it scale?

See:
 http://shipilev.net/blog/2014/safe-public-construction/

-Aleksey





_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Peter
In reply to this post by nader
To clarify, I'd have to separate the code I've authored, or contact the other author, in order to donate the entire works under the gpl.

Sent from my Samsung device.
 
---- Original message ----
From: Peter <[hidden email]>
Sent: 03/03/2016 09:31:02 am
To: AlekseyShipilev <[hidden email]>; NaderAeinehchi <[hidden email]>; concurrency-interest <[hidden email]>
Subject: Re: [concurrency-interest] Is this a pattern or an anti-pattern for check-and-act?

 There's an example of unsafe publication in java.security.Permissions, on occassion this class cannot resolve UnresolvedPermission, because the field hasUnresolved on line 96 is accessed under race conditions.

This class was written as a work around:

https://github.com/pfirmstone/river-internet/blob/trunk/src/org/apache/river/api/security/ConcurrentPermissions.java

There's a number of similar bugs in the  security infrastructure, most are masked by external synchronization.

We have our own policy provider that works around 95% of these issues by thread confining all PermissionCollection instances.

The policy provider relies on final fields for safe publication of Permission instances (after lazy initialisers are deliberately invoked).

PermissionCollection instances are created and discarded within method local scope.

CPU consumption of this policy provider is about 0.1% and is highly scalable in comparison the standard policy provider that consumes 10% cpu and limits scalability of applications.

https://github.com/pfirmstone/river-internet/blob/trunk/src/org/apache/river/api/security/ConcurrentPolicyFile.java

I can donate the policy provider and some required classes under the gpl, but cannot donate the policy file parser as it includes AL2 code written by others.  I've signed a contributor agreement.

Regards,

Peter.


Sent from my Samsung device.
 
---- Original message ----
From: Aleksey Shipilev <[hidden email]>
Sent: 01/03/2016 06:31:24 am
To: Nader Aeinehchi <[hidden email]>; concurrency-interest <[hidden email]>
Subject: Re: [concurrency-interest] Is this a pattern or an anti-pattern for check-and-act?

On 02/29/2016 10:17 PM, Nader Aeinehchi wrote:
> I saw this pattern on an open source project, and wonder if it is thread
> safe?  If so, would it scale?

See:
 http://shipilev.net/blog/2014/safe-public-construction/

-Aleksey






_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: Is this a pattern or an anti-pattern for check-and-act?

Millies, Sebastian
In reply to this post by Aleksey Shipilev-2
Here's a variation on the SafeLocalDCLFactory, where the synchronization has been replaced with CAS:

public class LockfreeFactory<T> {

    private AtomicReference<T> instance = new AtomicReference<>(null);

    public T getInstance(Supplier<T> s) {
        T i = instance.get();
        if (i == null) {
            i = s.get();
            if (!instance.weakCompareAndSet(null, i)) {
                i = instance.get();
            }
        }
        return i;
    }
}

Would this count as safe publication? I haven't mastered jcstress, but I'd be curious if it's faster than DCL.

-- Sebastian

-----Original Message-----
From: [hidden email] [mailto:[hidden email]] On Behalf Of Aleksey Shipilev
Sent: Monday, February 29, 2016 9:31 PM
To: Nader Aeinehchi; concurrency-interest
Subject: Re: [concurrency-interest] Is this a pattern or an anti-pattern for check-and-act?

On 02/29/2016 10:17 PM, Nader Aeinehchi wrote:
> I saw this pattern on an open source project, and wonder if it is
> thread safe?  If so, would it scale?

See:
 http://shipilev.net/blog/2014/safe-public-construction/

-Aleksey


Software AG – Sitz/Registered office: Uhlandstraße 12, 64297 Darmstadt, Germany – Registergericht/Commercial register: Darmstadt HRB 1562 - Vorstand/Management Board: Karl-Heinz Streibich (Vorsitzender/Chairman), Eric Duffaut, Dr. Wolfram Jost, Arnd Zinnhardt; - Aufsichtsratsvorsitzender/Chairman of the Supervisory Board: Dr. Andreas Bereczky - http://www.softwareag.com


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

FW: Is this a pattern or an anti-pattern for check-and-act?

Millies, Sebastian
In reply to this post by Aleksey Shipilev-2
Sorry, I think I was a bit hasty. The problem with this version it may happen that the code that actually constructs an object - s.get() - is called more than once. Laziness, however, is most useful if the object is a) perhaps not used and b) difficult to construct. So although the publication is safe, and the code will always return the same instance, in view of point b), this version does not really make sense as a singleton pattern. Right? -- Sebastian

> -----Original Message-----
> From: Millies, Sebastian
> Sent: Friday, March 04, 2016 2:02 PM
> To: concurrency-interest
> Cc: 'Aleksey Shipilev'; Nader Aeinehchi
> Subject: RE: [concurrency-interest] Is this a pattern or an anti-pattern for
> check-and-act?
>
> Here's a variation on the SafeLocalDCLFactory, where the synchronization has
> been replaced with CAS:
>
> public class LockfreeFactory<T> {
>
>     private AtomicReference<T> instance = new AtomicReference<>(null);
>
>     public T getInstance(Supplier<T> s) {
>         T i = instance.get();
>         if (i == null) {
>             i = s.get();
>             if (!instance.weakCompareAndSet(null, i)) {
>                 i = instance.get();
>             }
>         }
>         return i;
>     }
> }
>
> Would this count as safe publication? I haven't mastered jcstress, but I'd be
> curious if it's faster than DCL.
>
> -- Sebastian
>
> -----Original Message-----
> From: [hidden email] [mailto:concurrency-
> [hidden email]] On Behalf Of Aleksey Shipilev
> Sent: Monday, February 29, 2016 9:31 PM
> To: Nader Aeinehchi; concurrency-interest
> Subject: Re: [concurrency-interest] Is this a pattern or an anti-pattern for
> check-and-act?
>
> On 02/29/2016 10:17 PM, Nader Aeinehchi wrote:
> > I saw this pattern on an open source project, and wonder if it is
> > thread safe?  If so, would it scale?
>
> See:
>  http://shipilev.net/blog/2014/safe-public-construction/
>
> -Aleksey


Software AG – Sitz/Registered office: Uhlandstraße 12, 64297 Darmstadt, Germany – Registergericht/Commercial register: Darmstadt HRB 1562 - Vorstand/Management Board: Karl-Heinz Streibich (Vorsitzender/Chairman), Eric Duffaut, Dr. Wolfram Jost, Arnd Zinnhardt; - Aufsichtsratsvorsitzender/Chairman of the Supervisory Board: Dr. Andreas Bereczky - http://www.softwareag.com


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: FW: Is this a pattern or an anti-pattern for check-and-act?

nader
Hi

I have just created a repository on Github to document "common-mistakes-in-Java-concurrency".  I have thought to document the mistake, the solution(s) and possibly the code that breaks the mistake.

What do you think?  Any contribution is highly appreciated.

Best regards
Nader

On Fri, Mar 4, 2016 at 2:10 PM, Millies, Sebastian <[hidden email]> wrote:
Sorry, I think I was a bit hasty. The problem with this version it may happen that the code that actually constructs an object - s.get() - is called more than once. Laziness, however, is most useful if the object is a) perhaps not used and b) difficult to construct. So although the publication is safe, and the code will always return the same instance, in view of point b), this version does not really make sense as a singleton pattern. Right? -- Sebastian

> -----Original Message-----
> From: Millies, Sebastian
> Sent: Friday, March 04, 2016 2:02 PM
> To: concurrency-interest
> Cc: 'Aleksey Shipilev'; Nader Aeinehchi
> Subject: RE: [concurrency-interest] Is this a pattern or an anti-pattern for
> check-and-act?
>
> Here's a variation on the SafeLocalDCLFactory, where the synchronization has
> been replaced with CAS:
>
> public class LockfreeFactory<T> {
>
>     private AtomicReference<T> instance = new AtomicReference<>(null);
>
>     public T getInstance(Supplier<T> s) {
>         T i = instance.get();
>         if (i == null) {
>             i = s.get();
>             if (!instance.weakCompareAndSet(null, i)) {
>                 i = instance.get();
>             }
>         }
>         return i;
>     }
> }
>
> Would this count as safe publication? I haven't mastered jcstress, but I'd be
> curious if it's faster than DCL.
>
> -- Sebastian
>
> -----Original Message-----
> From: [hidden email] [mailto:[hidden email]
> [hidden email]] On Behalf Of Aleksey Shipilev
> Sent: Monday, February 29, 2016 9:31 PM
> To: Nader Aeinehchi; concurrency-interest
> Subject: Re: [concurrency-interest] Is this a pattern or an anti-pattern for
> check-and-act?
>
> On 02/29/2016 10:17 PM, Nader Aeinehchi wrote:
> > I saw this pattern on an open source project, and wonder if it is
> > thread safe?  If so, would it scale?
>
> See:
http://shipilev.net/blog/2014/safe-public-construction/
>
> -Aleksey


Software AG – Sitz/Registered office: Uhlandstraße 12, 64297 Darmstadt, Germany – Registergericht/Commercial register: Darmstadt HRB 1562 - Vorstand/Management Board: Karl-Heinz Streibich (Vorsitzender/Chairman), Eric Duffaut, Dr. Wolfram Jost, Arnd Zinnhardt; - Aufsichtsratsvorsitzender/Chairman of the Supervisory Board: Dr. Andreas Bereczky - http://www.softwareag.com



_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest
Reply | Threaded
Open this post in threaded view
|

Re: FW: Is this a pattern or an anti-pattern for check-and-act?

Aleksey Shipilev-2
On 03/04/2016 05:10 PM, Nader Aeinehchi wrote:
> I have just created a repository on Github to document
> "common-mistakes-in-Java-concurrency".  I have thought to document the
> mistake, the solution(s) and possibly the code that breaks the mistake.
>
> What do you think?  Any contribution is highly appreciated.

Documenting "bad" cases gets much better exposure with CERT:

https://www.securecoding.cert.org/confluence/display/java/LCK10-J.+Use+a+correct+form+of+the+double-checked+locking+idiom

The maintainers there seem open to additions and corrections.

Thanks,
-Aleksey


_______________________________________________
Concurrency-interest mailing list
[hidden email]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest

signature.asc (853 bytes) Download Attachment
12