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

1

6

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.

Chibouk answered 17/4, 2013 at 21:30 Comment(1)
possible duplicate of Thoughts in accessing read only objects from different threadsChibouk
P
2

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.

Pettitoes answered 17/4, 2013 at 22:40 Comment(3)
Thanks for your reply. +1. I will wait for other replies for a while before marking yours as correct. Thanks.Chibouk
I created a new question on it. #19960787. This is the correct answer. Cheers.Chibouk
So, please think to remove your answer as not correct. Thanks.Chibouk

© 2022 - 2024 — McMap. All rights reserved.