Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 599759
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T16:31:58+00:00 2026-05-13T16:31:58+00:00

Which one synchronization method to use to ensure a singleton remains a singleton? +(Foo*)sharedInstance

  • 0

Which one synchronization method to use to ensure a singleton remains a singleton?

+(Foo*)sharedInstance
{
   @synchronized(self)
   {
      if (nil == _sharedInstance)
      {
         _sharedInstance = [[Foo alloc] init];
         ...
      }
   }
   return _sharedInstance;
}

or using a mutex?

#import <pthread.h>

static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;

+(Foo*)sharedInstance
{
   pthread_mutex_lock(&_mutex);
   if (nil == _sharedInstance)
   {
      _sharedInstance = [[Foo alloc] init];
      ...
   }
   pthread_mutex_unlock(&_mutex);
   return _sharedInstance;
}

Hmmm.. any comments on this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T16:31:59+00:00Added an answer on May 13, 2026 at 4:31 pm

    Make sure you read the discussion on this question/answer, too. Why should we separate alloc and init calls to avoid deadlocks in Objective-C?


    To expand on the race condition issue; the real fix is to not have indeterminate initialization within your application. Indeterminate or lazy initialization results in behavior that can easily change due to seemingly innocuous changes — configuration, “unrelated” code changes, etc…

    Better to explicitly initialize subsystems on a known-good point in the program’s lifespan. I.e. drop [MyClass sharedInstance]; into your App delegate’s applicationDidFinishLaunching: method if you really need that subsystem initialized early in the program (or move it even earlier, if you want to be extra defensive).

    Better still to move initialization out of that method entirely. I.e. [MyClass initializeSharedInstance]; where +sharedInstance asserts() if that method isn’t called first.

    As much as I’m a a fan of convenience, 25 years of ObjC programming has taught me that lazy initialization is a source of more maintenance and refactoring headaches than it is worth.


    While the race condition described below exists, this code doesn’t fix what is described below. It did for a couple of decades when we didn’t worry about concurrency in shared instance initializers. Leaving the wrong code for prosperity.

    Keep in mind that for both Colin’s and Harald’s otherwise correct answers, there is a very subtle race condition that could lead you to a world of woe.

    Namely, if the -init of the class being allocated happens to call the sharedInstance method, it will do so before the variable is set. In both cases it will lead to a deadlock.

    This is the one time that you want to separate the alloc and the init. Cribbing Colin’s code because it is the best solution (assuming Mac OS X):

    +(MyClass *)sharedInstance
    {   
        static MyClass *sharedInstance = nil;
        static dispatch_once_t pred;
    
        // partial fix for the "new" concurrency issue
        if (sharedInstance) return sharedInstance;
        // partial because it means that +sharedInstance *may* return an un-initialized instance
        // this is from https://stackoverflow.com/questions/20895214/why-should-we-separate-alloc-and-init-calls-to-avoid-deadlocks-in-objective-c/20895427#20895427
    
        dispatch_once(&pred, ^{
            sharedInstance = [MyClass alloc];
            sharedInstance = [sharedInstance init];
        });
    
        return sharedInstance;
    }
    

    note this only works on Mac OS X; X 10.6+ and iOS 4.0+, in particular. On older operating systems, where blocks are not available, use a lock or one of the various means of doing something once that isn’t blocks based.


    The above pattern does not actually prevent the problem described in the text and will cause a deadlock when it is encountered. The problem is that the dispatch_once() is not re-entrant and, thus, if the init calls sharedInstance, wedge city.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 381k
  • Answers 382k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer EBX is the 32-bit variant BX is the 16-bit variant… May 14, 2026 at 10:20 pm
  • Editorial Team
    Editorial Team added an answer Ghostscript is available also for windows. You can test It… May 14, 2026 at 10:20 pm
  • Editorial Team
    Editorial Team added an answer the "duplicate specification of attribute "value"" simply isn't true according… May 14, 2026 at 10:20 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.