Help understanding class method returning singleton [duplicate]
Asked Answered
B

4

12

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;
}
Boldt answered 4/6, 2011 at 2:36 Comment(0)
J
46

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 +shared method at the same exact moment. You wouldn't want one thread to be modifying the single sharedSingleton variable 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 the Game class has an instance variable named players which is an NSMutableArray of instances of a Player class. Let's say the Game class had an -addPlayer: method, which would modify the players instance 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 the players array at a time. So, the implementation of that method might look something like this:

- (void)addPlayer:(Player *)player {
   if (player == nil) return;
   @synchronized(players) {
      [players addObject:player];
   }
}

Using the @synchronized() directive makes sure only one thread can access the players variable 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 self in the @synchronized(self) line in the following code basically equates to the Game class itself. By synchronizing on the Game class, it assures that the sharedSingleton = [[Game alloc] init]; line is only ever called once.

+ (Game *) shared
{
    static Game *sharedSingleton;

    @synchronized(self) // assures only one thread can call [Game shared] at a time
    {
        if (!sharedSingleton)
        {
            sharedSingleton = [[Game alloc] init];
        }
    }

    return sharedSingleton;
}

[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:

Game *sharedInstance;

@implementation Game
+ (Game *)sharedGame {
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[[self class] alloc] init];
        }
    }
    return sharedInstance;
}
@end

Outside @implementation, static:

static Game *sharedInstance;

@implementation Game
+ (Game *)sharedGame {
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[[self class] alloc] init];
        }
    }
    return sharedInstance;
}
@end

Inside @implementation:

@implementation Game

static Game *sharedInstance;

+ (Game *)sharedGame {
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[[self class] alloc] init];
        }
    }
    return sharedInstance;
}
@end

Inside +sharedGame:

@implementation Game
+ (Game *)sharedGame {
    static Game *sharedInstance;
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[[self class] alloc] init];
        }
    }
    return sharedInstance;
}
@end

The only difference is that in the first variation, without the static keyword, sharedInstance doesn't show up under File Statics in gdb. And obviously, in the last variation, sharedInstance isn't visible outside of the +sharedGame method. But practically speaking, they all assure that when you call [Game sharedInstance] you'll get back the sharedInstance, and that the sharedInstance is only created once. (Note, however, that further precautions would be needed to prevent someone from creating a non-singleton instance using something like Game *game = [[Game alloc] init];).

Jebel answered 4/6, 2011 at 4:56 Comment(4)
Shouldn't the declaration, static Game *sharedSingleton; be outside + (Game *)shared scope?Whang
@Peter: updated with more info regarding where sharedSingleton is defined. I generally like to put it outside, though.Jebel
Thank you for taking time for testing these different cases. I didn't know all these ways to declare static *sharedSingleton are valid. For stronger encapsulation, I think I should start declaring the singleton inside the + (Game *)sharedGame; scope. Good thing to learn.Whang
Sorry, but I have this example and I don't understand the meaning: ` Integer i1 = Arrays.asList(1,2,3,4,5).stream().findAny().get(); synchronized(i1) { Integer i2 = Arrays.asList(6,7,8,9,10) .parallelStream() .sorted() .findAny().get(); System.out.println(i1+" "+i2); }` 1. Why did you invoke the block on the first instance and this invocation has no effect on the code? 2. The second instance will be thread-safe, despite the invocation of the block on the first?Rambling
B
9

A row-by-row explanation ...

// A static variable guarantees there's only 1 instance of it ever, 
// even accross multiple instances of the same class, this particular
// variable will store the class instance, so it can be returned whenever
// a client-class requests an instance of this class.
static Game *sharedSingleton;

// create a method that can always be called, even if there's no instance yet
// this method should create a new instance if there isn't one yet, otherwise
// return the existing instance
+ (Game *) shared  
{
    // synchronized makes sure only 1 client class can enter this method at any time, 
    // e.g. to prevent creating 2 instances whenever 2 client-classes try to 
    // access the following code from different threads.
    @synchronized(self)
    {
        // if the static variable is called for the first time, 
        // create an instance and return it, otherwise return the existing instance ...
        if (!sharedSingleton)
        {
            sharedSingleton = [[Game alloc] init];
        }
    }

    return sharedSingleton;
}
Balas answered 4/6, 2011 at 7:50 Comment(1)
Sorry, but I have this example and I don't understand the meaning: ` Integer i1 = Arrays.asList(1,2,3,4,5).stream().findAny().get(); synchronized(i1) { Integer i2 = Arrays.asList(6,7,8,9,10) .parallelStream() .sorted() .findAny().get(); System.out.println(i1+" "+i2); }` 1. Why did you invoke the block on the first instance and this invocation has no effect on the code? 2. The second instance will be thread-safe, despite the invocation of the block on the first?Rambling
B
3

I don't know much Objective-C, but it appears to be a method for getting a singleton copy of the type Game* and is intended to be thread-safe.

Essentially calling that method will return the same copy of Game* every-time (regardless of which thread) and will not allocate a new instance of Game until the first time it is called (known as lazy-loading)

Buckingham answered 4/6, 2011 at 2:40 Comment(0)
G
3

I would also override ’mutableCopyWithZone:’ and ’copyWithZone:’ methods in order to avoid that the singleton get copied:

// copy cannot be done
- (Game *)copyWithZone:(NSZone *)zone {
    return self;
}
// mutablecopy cannot be done
- (Game *)mutableCopyWithZone:(NSZone *)zone {
    return [self copyWithZone:zone];
}

Since ’copy’ and ’mutableCopy’ (assuming the singleton class doesn't inherit from another class which has overridden default NSObject implementations) just call ’copyWithZone:’ and ’mutableCopyWithZone:’ there will be not need to override those too.

To also avoid other developers from breaking the singleton pattern by using ’init’ or ’new’, the two methods can be declared unavailable:

- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;

In this way the compiler won't allow the use of the two methods, and other developers will be forced to use the documented method for obtaining the shared instance. Another —more strict— technique is to override ’init’ and ’new’ and raise an exception.

Gaekwar answered 27/2, 2017 at 0:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.