Are my Objective-C singletons thread safe? - objective-c

I've been reading around and its hard to get a clear feel if I have written a thread safe implementation here.
My getter looks like
+ (MySingleton *)getSingleton
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleton = [[MySingleton alloc] init];
});
return singleton;
}
And my setter is:
+ (void)updateSingleton:(MySingleton *)newSingleton
{
#syncronized(self) {
singleton = newSingleton;
}
}

No, that isn't thread safe. Your exclusion mechanism between your two modification methods are not the same. dispatch_once has nothing to do with #synchronized in any way.
Beyond that a singleton must never be replaced by definition. A singleton can come into existence at any time and, once it does, it never, ever, goes away.
Also, getSingleton should be sharedInstance or some similar objective-c standard moniker. Methods should never be prepended with get unless they are returning stuff by reference.

Related

dispatch_once vs runtime check for once initialized property

What is the difference between dispatch_once and using runtime conditional check for the property that requires only once initialization
Method 1: runtime checking
- (MyProp *)myProp{
if (!_myProp){
_myProp = [[MyProp alloc] init];
}
return _myProp;
}
Method 2: use dispatch_once
- (MyProp *)myProp{
dispatch_once_t once;
dispatch_once(&once, ^{
_myProp = [[MyProp alloc] init];
}
return _myProp;
}
I guess that method 2 is somehow faster but not really sure.
Could anyone give me any deal?
Thanks
dispatch_once is thread safe. So if two threads call myProp for the first time simultaneously, dispatch_once ensures only one initializes the variable. Method 1 may initialize the variable twice, and could even corrupt memory such that the reference is invalid. Once the property has been initialized, these behave identically.
Method 2 is actually slightly slower than Method 1, particularly during the first initialization. But in the usual case (reading after initialization), it is extremely close (possibly identical) in performance. If you want a much more in-depth exploration of how it works and why, see Mike Ash's Secrets of dispatch_once.
Note that your Method 2 code is incorrect. You've made once an automatic local variable. It needs to be static or dispatch_once can't do its job. What you meant was:
- (MyProp *)myProp{
static dispatch_once_t once; // <--- this "static" is critical
dispatch_once(&once, ^{
_myProp = [[MyProp alloc] init];
}
return _myProp;
}

How can I multithread the creation of a lazily loaded property?

- (NSHashTable *)pollers
{
if (!_pollers) {
dispatch_sync(self.serialQueue, ^{
_pollers = [NSHashTable weakObjectsHashTable];
});
}
return _pollers;
}
pollers is a nonatomic property on a singleton. There are some other methods in the singleton where objects are added to pollers, and I'm using #synchronized for their addition ([self.pollers addObject:____]).
Anyway... I have a question about the code above. If 2 threads simultaneously call this function, they could both get past the if (!_pollers) code, and then both will dispatch the _pollers = [NSHashTable weakObjectsHashTable]; code synchronously on our custom serialQueue. So we'll actually run the code twice.
Is there a better way to do this?
You only need a single dispatch_once function for this
Your serial queue is now redundant, as dispatch_once will ensure that the block is only called once (even if invoked at the same time from multiple threads), contrary to what pds says.
The documentation clearly states that:
If [dispatch_once is] called simultaneously from multiple threads, this function waits synchronously until the block has completed.
Your if statement is also redundant, as pointed out by Josh.
Therefore you just want:
- (NSHashTable *)pollers
{
static dispatch_once_t t;
dispatch_once(&t, ^{
_pollers = [NSHashTable weakObjectsHashTable];
});
return _pollers;
}
It's also worth noting that you'll need a thread safe implementation of your singleton's sharedInstance in order for this to be bulletproof. You can do this in much the same way with a dispatch_once. For example:
static singleton* sharedInstance;
+(instancetype) sharedInstance {
static dispatch_once_t t;
dispatch_once(&t, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
Use dispatch_once like this
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dispatch_sync(self.serialQueue, ^{
_pollers = [NSHashTable weakObjectsHashTable];
});
});
return pollers;

Proper Singleton Implementation

I'm reading through a book trying to brush the dust off of Objective-C, and I ran into this question while reading how to implement a singleton. This is the implementation as they have it in the book:
+ (ClassName *)sharedClass {
static ClassName *sharedClass = nil;
if (!sharedClass) {
sharedClass = [[super allocWithZone:nil] init];
return shared store
}
My question is, why would they set it to nil each time the method is ran, then check if it's nil, which it now obviously is, and create a new instance? That sounds like it defeats the whole purpose of a singleton, to only have one instance of a class. I've noticed a ton of questions related to singleton implementation, but none specific to this aspect of it. Believe me, I combed through before posting.
The static variable is set to nil only for the first time. Once the sharedClass instance is instantiated, you will alway have the same instance whenever you invoke [ClassName sharedClass].
You should use thread-safe pattern to use singleton pattern.
+ (instancetype)shared {
static id shared = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shared = [[self alloc] init];
});
return sharedInstance;
}
This will prevent possible crashes.

Difference creating Singleton by class method and instance method

What are the implications of creating a singleton class with:
+ (id)sharedCoordinator {
static MyCoordinator *sharedCoordinator = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedCoordinator = [[self alloc] init];
});
}
or as an instance method in the Application Delegate with class method:
- (CoreDataHelper *)cdh {
if (!_coreDataHelper) {
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
_coreDataHelper = [CoreDataHelper new];
});
[_coreDataHelper setupCoreData];
}
return _coreDataHelper;
}
I have seen them both used, and would like to learn how they affect performance, simple code, debugging, etc.
The main difference is that the second code snippet has an error: when cdh is accessed concurrently from multiple threads, there is a possibility of [_coreDataHelper setupCoreData] being called twice.
This would happen if multiple threads arrived at cdh at the time when _coreDataHelper is nil. Only one of these threads would proceed to make the [CoreDataHelper new] call, yet all threads would end up in the setupCoreData method.
The proper way of doing initialization is to place the setup call into the block, and make the call unconditional:
- (CoreDataHelper *)cdh {
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
_coreDataHelper = [CoreDataHelper new];
[_coreDataHelper setupCoreData];
});
return _coreDataHelper;
}
Now the two snippets look almost identical. The only difference is that the first snippet uses a method-static variable to store the singleton, while the updated second snippet "piggybacks" on the instance of app delegate.
This does not create any performance differences worth discussing. The biggest difference is that the first snippet lets you access the singleton without creating an additional dependency on the app delegate, which is a good thing: this avoids "polluting" your app delegate with code that is not directly relevant to the application state.
The first allows the Singleton class to be re-used in other places.
The second makes the single instance private to the app delegate.
Generally the first option is better (IMHO.) It allows you to reuse the single instance in a structured way anywhere in your code.
The second option can provide a guarantee of being a single instance, privately accessible in one place. That is probably useful in some circumstances, but it isn't really a Singleton. You could make this a public property on the AppDelegate, but then why not use a Singleton class?
As for performance considerations, they should be negliable. The only one I can think of is the slight extra overhead in the runtime caused by having an extra class object in your code.

What does Singleton example in Apple's documentation actually do?

Can Someone explain me few things regarding the Singleton implementation in Apple's documentation here.
Link: - http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html
Go to Creating a Singleton Instance in the link.
I tried but couldn't understand few things:-
What does [super allocWithZone:NULL] in + (MyGizmoClass*)sharedManager does.?
Why does allocWithZone call sharedManger method and return a retain call on its return type when retain itself returns self ?
If the Singleton has some instance variables in it, where should they be initialized ?
If anyone could briefly explain working of allocWithZone and sharedManager methods here , a lot of these questions would automatically be answered.
That implementation is generally considered over_kill. There is a lot of protections against a programmer trying to mis-use the singleton which is generally not considered necessary.
Here is an example of a more simple implementation from Yoga:
+ (id)sharedFoo
{
static dispatch_once_t once;
static MyFoo *sharedFoo;
dispatch_once(&once, ^ { sharedFoo = [[self alloc] init]; });
return sharedFoo;
}
Here goes - I have paraphrased your questions:
What does [super allocWithZone:NULL] do?
This is the same as saying [super alloc]. The withZone part is to do with where in memory your object will be stored. In practice, it would be very rare to use it. See this question for more info - what is difference between alloc and allocWithZone:?
Why does the retain method return itself (and not increment the retain counter)
Singletons are kept alive throughout the life of your application - you don't care about the retain count, because there's no situation in which you would want to deallocate your singleton. retain returns self as a courtesy and convention (and to allow nested expressions).
If the Singleton has some instance variables in it, where should they be initialized ?
Up to you. Typically you would initialise them in the init method, as per a normal object.