• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: How to implement readonly property
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to implement readonly property


  • Subject: Re: How to implement readonly property
  • From: Ken Thomases <email@hidden>
  • Date: Fri, 07 Dec 2012 20:57:40 -0600

On Dec 7, 2012, at 8:01 PM, Steve Sisak wrote:

> Here's what I usually do:
>
> assume that _someDictionary is an instance variable initialized to nil and never changed once initialized to non-nil
>
> - (NSDictionary *)someDictionary;
> {
>  if (!_someDictionary)
>  {
>    @synchronized (self)
>    {
>      if (!_someDictionary)
>      {
>        // create a temp dictionary (might take some time)
>         _someDictionary = temp;
>      }
>    }
>  }
>
>  return _someDictionary;
> }
>
> the outer if avoids the overhead of @synchronized if _someDictionary is already created -- this is just an optimization
>
> the inner if is necessary to resolve the race condition if multiple threads make it past the outer one

This is a classic anti-pattern called double-checked locking.  It is not safe.  Don't rely on it.
https://en.wikipedia.org/wiki/Double-checked_locking
http://erdani.com/publications/DDJ_Jul_Aug_2004_revised.pdf

Regards,
Ken


_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden

  • Follow-Ups:
    • Re: How to implement readonly property
      • From: Steve Sisak <email@hidden>
References: 
 >Re: How to implement readonly property (From: Steve Sisak <email@hidden>)

  • Prev by Date: Re: How to implement readonly property
  • Next by Date: Re: How to implement readonly property
  • Previous by thread: Re: How to implement readonly property
  • Next by thread: Re: How to implement readonly property
  • Index(es):
    • Date
    • Thread