Can someone please help me understand what the following method is doing?
+ (Game *) shared
{
static Game *sharedSingleton;
@synchronized(self)
{
if (!sharedSingleton)
{
sharedSingleton = [[Game alloc] init];
}
}
return sharedSingleton;
}
Obviously, the idea behind a singleton is to create only a single instance. The first step in achieving this is to declare a static instance of the class via the line
static Game *sharedSingleton;.The second step is to check whether the single instance is already created, and if it isn’t, to create it, or if it is, to return the existing single instance. However, this second step opens up the potential for problems in the event that 2 separate threads try to call the
+sharedmethod at the same exact moment. You wouldn’t want one thread to be modifying the singlesharedSingletonvariable while another thread is trying to examine it, as it could produce unexpected results.The solution to this problem is to use the
@synchronized()compiler directive to synchronize access to the object specified between the parenthesis. For example, say this single shared instance of theGameclass has an instance variable namedplayerswhich is anNSMutableArrayof instances of aPlayerclass. Let’s say theGameclass had an-addPlayer:method, which would modify theplayersinstance variable by adding the specified player. It’s important that if that method were called from multiple threads, that only one thread be allowed to modify theplayersarray at a time. So, the implementation of that method might look something like this:Using the
@synchronized()directive makes sure only one thread can access theplayersvariable at a time. If one thread attempts to while another thread is currently accessing it, the first thread must wait until the other thread finishes.While it’s more straightforward when you’re talking about an instance variable, it’s perhaps less clear how to achieve the same type of result within the single creation method of the class itself. The
selfin the@synchronized(self)line in the following code basically equates to theGameclass itself. By synchronizing on theGameclass, it assures that thesharedSingleton = [[Game alloc] init];line is only ever called once.[EDIT]: updated. Based on my tests a while back (and I just re-tested it now), the following all appear to be equivalent:
Outside
@implementation:Outside
@implementation,static:Inside
@implementation:Inside
+sharedGame:The only difference is that in the first variation, without the
statickeyword,sharedInstancedoesn’t show up under File Statics ingdb. And obviously, in the last variation,sharedInstanceisn’t visible outside of the+sharedGamemethod. But practically speaking, they all assure that when you call[Game sharedInstance]you’ll get back thesharedInstance, and that thesharedInstanceis only created once. (Note, however, that further precautions would be needed to prevent someone from creating a non-singleton instance using something likeGame *game = [[Game alloc] init];).