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 7022339
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T23:34:09+00:00 2026-05-27T23:34:09+00:00

How does one create a thread safe singleton object in objective-c. for eg. If

  • 0

How does one create a thread safe singleton object in objective-c. for eg. If I have a shared data controller which is a singleton object what will happen if two or more threads are accessing it at the same time..? Or these objects have thread safety by default..?

update:

Is it under this scenario that the objects inside the datacontroller’s property decide if it is thread safe or not.. ? Like my datacontroller has NSMutableArray and it is set nonatomic it will not be thread safe. What will happen to its value in that case?

update:2

And what actually does @synchronized(self) do..?

  • 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-27T23:34:10+00:00Added an answer on May 27, 2026 at 11:34 pm

    If the data controller is not threadsafe, then undefined behavior could happen — avoid it at all costs =)

    NSObjects are definitely not threadsafe by default. Using atomic properties does not make a class threadsafe (added that because it’s a popular misconception).

    The typical solution would involve making sure that all of your mutable state is protected with appropriate locking (e.g. a mutex or @synchronized).

    When I say mutable state, I am referring to an object which can mutate externally or internally. If you are not sure, lock to be sure the types are read or written from multiple threads. This must happen at reading and writing – always. If you have a lot of reading, a readwrite lock may be a better, more specialized lock.

    To answer in more detail, you’d have to post some code.

    Update

    Is it under this scenario that the objects inside the datacontroller’s property decide if it is thread safe or not.. ? Like my datacontroller has NSMutableArray and it is set nonatomic it will not be thread safe. What will happen to its value in that case?

    Think of it as being transitive. Your NSMutableArray, the objects it holds, and all external references to them must be used in a threadsafe manner, and you have to track all that. Typically, you start by reducing what mutable state you share. Instead of giving clients a reference to the array, give them copies of the elements held by the array. Meanwhile, protect all reads, writes, and element copying with a lock.

    For simplicity, I will demonstrate using @synchronize:

    @interface MONCookie : NSObject <NSCopying>
    
    - (NSString *)name;
    
    @end
    
    @interface MONDataController : NSObject
    {
    @private
      NSMutableArray * cookies; // << MONCookie[]
    }
    
    - (void)addCookie:(MONCookie *)cookie;
    
    - (MONCookie *)cookieWithName:(NSString *)name;
    
    @end
    
    @implementation MONDataController
    
    - (id)init
    {
      // no lock required here
      self = [super init];
      if (nil != self) {
        cookies = [NSMutableArray new];
      }
      return self;
    }
    
    - (void)dealloc
    {
      // no lock required here
      [cookies release], cookies = nil;
      [super dealloc];
    }
    
    - (void)addCookie:(MONCookie *)cookie
    {
      @synchronized(self) { // now accessing cookies - lock required
        [cookies addObject:cookie];
      }
    }
    
    - (MONCookie *)cookieWithName:(NSString *)name
    {
      MONCookie * ret = nil;
      @synchronized(self) { // now accessing cookies - lock required
        for (MONCookie * at in cookies) {
          if ([at.name isEqualToString:name]) {
            ret = [at copy]; // << give them a copy if cookie is not threadsafe
          }
        }
      }
      return [ret autorelease];
    }
    
    @end
    

    Update 2

    @synchronized sets up an object level lock. You can think of it as a recursive (or reentrant) lock exclusive to your instance. It’s also quite slow compared to other locking approaches. The code above uses it, and it is threadsafe and equivalent to holding a recursive lock, and locking and unlocking at the @synchronized boundaries.

    @interface MONCookie : NSObject <NSCopying>
    {
    @private
        NSRecursiveLock * lock;
    }
    
    @end
    
    @implementation MONCookie
    
    - (id)init
    {
        self = [super init];
        if (nil != self) {
            lock = [NSRecursiveLock new];
        }
        return self;
    }
    
    - (void)temperatureDidIncrease
    {
        // ...  
    }
    
    - (void)bake
    {
        // use the same lock for everything
        // do not mix @synchronized in some places, and use of the lock 
        // in others. what you use to protect the data must remain consistent
        //
        // These are equivalent approaches to protecting your data:
    
        {   // @synchronized:
            @synchronized(self) {
                [self temperatureDidIncrease];  
            }
        }
    
        {   // using the lock:
            [lock lock];
            [self temperatureDidIncrease];  
            [lock unlock];
        }
    }
    
    @end
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two questions about creating thread safe types in python, and one related
Does SQL Server 2005 create one thread per connection? or How does it manage
How does one create Dynamic CSS and JavaScript On-The-Fly (using PHP). This needs to
How does one create a package for a Java Project through the Unix command-line?
Does startService() create a new Service instance or using the existing one? For example,
How does one go about programatically building a TemplateColumn object and adding it to
I'm using Thread::Pool::Simple to create a few working threads. Each working thread does some
i'm creating asmx web service and have to create thread to do background IO
Given: Constructing an ADO Connection object from one thread and giving it to another
Does SqlCommand.Clone() create a deep copy or shallow copy? Also, is it safe to

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.