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

笑着哭i 提交于 2019-12-19 07:55:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/16070597/doubts-on-concurrency-with-objects-that-can-be-used-multiple-times-like-formatte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!