objective c - Lazy-loading and thread-safe dictionary -


i use pattern:

@property (nonatomic, readwrite, strong) nsmutabledictionary * mutabledictionary;  [...]  - (id)objectforkey:(nsstring *)key {     id result = self.mutabledictionary[key];      if (!result)     {         result = [...] ; // go , fetch result;          self.mutabledictionary[key] = result;     }      return result ; } 

but realized not thread-safe. have similar lazy-loading pattern thread-safe.

what best way achieve that?

i use nslock objects. easy use. wrap setter of mutabledictionary in it.

@property (nonatomic, readwrite, strong) nsmutabledictionary * mutabledictionary;  nslock *mutexlock = [nslock new]; [...]  - (id)objectforkey:(nsstring *)key {     id result = self.mutabledictionary[key];      if (!result)     {         [mutexlock lock];         result = [...] ; // go , fetch result;         self.mutabledictionary[key] = result;         [mutexlock unlock];     }      return result ; } 

update: assumes in //go fetch results not thread safe.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -