Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubts on concurrency with objects that can be used multiple times like formatters

Maybe a stupid question to ask but I need some confirmations on it.

Usually, when I deal with objects that can be used multiple times within my application I use an approach like the following.

Create an extension, say for example NSDecimalNumber+Extension, or a class utility where a number formatter is created like the following.

+ (NSNumberFormatter*)internal_sharedNumberFormatter
{
    static NSNumberFormatter* _internal_numberFormatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _internal_numberFormatter = [[NSNumberFormatter alloc] init];
        // other configurations here...
    });

    return _internal_numberFormatter;
}

+ (NSString*)stringRepresentationOfDecimalNumber:(NSDecimalNumber*)numberToFormat
{
    NSString *stringRepresentation = [[self class] internal_sharedNumberFormatter] stringFromNumber:numberToFormat];
    return stringRepresentation;
}

This approach is quite good since, for example, formatters are expensive to create. But it could be applied to other situations as well.

Now, my questions is the following.

Does this approach is also valid in situations where different path of execution (different threads) are involved?

So, if I call first stringRepresentationOfDecimalNumber on the main thread and then in a different thread, what could happen?

I think is valid to perform different calls to stringRepresentationOfDecimalNumber in different threads since the shared formatter, in this case, is reading only, but I would like to have a reply from experts.

Thanks in advance.

like image 263
Lorenzo B Avatar asked Nov 03 '22 23:11

Lorenzo B


1 Answers

NSNumberFormatter is mutable, so it is generally not thread safe and cited in Thread Safety Summary (see the "Thread-Unsafe Classes" section) in the non thread safe classes list.

But if you treat your object as an immutable object, you don't have to worry about race conditions. So for example, you cannot change the format if there are multiple threads accessing the formatter. If _internal_numberFormatter isn't altered in any way, and you have just these two methods in the category, you should consider it thread safe.

like image 85
Ramy Al Zuhouri Avatar answered Nov 15 '22 07:11

Ramy Al Zuhouri