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
Post a Comment