Thoughts on read-only access to objects from different threads

Based on the previous discussion I had in SO (see Doubts about concurrency with objects that can be used several times, such as formatting ), here I ask a more theoretical question about objects that are created once during the application life cycle (and never change, therefore, are read-only) and can be accessed from different threads. A simple option is Core Data. Formats can be used in different streams (main stream, import stream, etc.).

NSFormatters, for example, are extremely expensive to create. Based on this, they can be created once, and then reused. A typical template that can be executed (also highlighted by @mattt in NSFormatter is as follows.

+ (NSNumberFormatter *)numberFormatter {
    static NSNumberFormatter *_numberFormatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _numberFormatter = [[NSNumberFormatter alloc] init];
        [_numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    });

    return _numberFormatter;
}

Even if I’m sure that this is a very good approach to execution (some object is created that is read-only / immutable), formatters are not thread safe, so using them in thread safe mode can be dangerous. I found a discussion of the argument in NSDateFormatter crash when used from different threads , where the author noticed that a crash could happen.

NSDateFormatters are not thread safe; there was a background thread trying to use the same formatter at the same time (hence the randomness).

, ? ?

+4
2

:

iOS 7/OSX 10.9 . ICU , , , .

iOS 7/OSX 10.9, NSDateFormatter NSNumberFormatter ICU, .

:

/, , , , , , .

. , , .

(, )

// in the dispatch_once where you create the formatter
dispatch_queue_t formatterQueue = dispatch_queue_create("date formatter queue", 0);

// where you use the formatter
dispatch_sync(formatterQueue, ^{ (do whatever you wanted to do with the formatter) });
+7

, ( , , )

: , , . , NSMutableArray , , .

, , . , , , . , NSDateFormatter : , , .

- : NSDateFormatter , : , 5,10% , .

+3

All Articles