I met this on Mike Ashe "Care and Nutrition for the Lonely" and was a little puzzled by his comment:
This code is a bit slow. Taking the castle is somewhat expensive. To make this more painful is the fact that the vast majority of the time, a castle is useless. Locking is only required when foo is zero, which is basically only once. After a singleton is initialized, the castle needs to be gone, but the castle itself remains.
+(id)sharedFoo { static Foo *foo = nil; @synchronized([Foo class]) { if(!foo) foo = [[self alloc] init]; } return foo; }
My question is, and there is no reason for this, but why can't you write (see below) to limit the lock when foo is nil?
+(id)sharedFoo { static Foo *foo = nil; if(!foo) { @synchronized([Foo class]) { foo = [[self alloc] init]; } } return foo; }
cheers gary
objective-c cocoa double-checked-locking
fuzzygoat
source share