I am trying to build a singleton caching class . Now i am stuck with a problem that , When two threads simultaneously accessing the methods in my singlton what will happen , is it will crash . Means in my class i have some methods that reads and writes to files from disk. So what's the best methods to overcome this situations . I have to use Locks or Syncronised methods .... Helps me to understand the things ..
Asked
Active
Viewed 109 times
0
-
So... Did you just answer your own question at the end there? – Corbin Dec 04 '11 at 10:22
-
is i have to use Locks or Syncronised methods ? ... can anyone point me any examples .... – Sachu Vijay Dec 04 '11 at 10:33
-
I would just use a lock around the underlying hash map. Not sure on the specific code since I've never done any Objective C stuff. Should be able to google for an example though. – Corbin Dec 04 '11 at 10:40
-
This post may be of help in understanding @synchronized [http://stackoverflow.com/questions/1215330/how-does-synchronized-lock-unlock-in-objective-c][1] [1]: http://stackoverflow.com/questions/1215330/how-does-synchronized-lock-unlock-in-objective-c – reddersky Dec 04 '11 at 14:03
-
Synchronized is slow, rather use OSAtomic: http://mikeash.com/pyblog/friday-qa-2011-03-04-a-tour-of-osatomic.html if you want to make sure something in the singleton runs only once at a time, or even better grand central dispatch queues – Kerni Dec 04 '11 at 21:23
1 Answers
0
Use dispatch_once
to guarantee that the initialization will only happen the first time the method is called.
+ (NSArray *)foo
{
static NSArray *_sharedFoo;
static dispatch_once_t count = 0;
dispatch_once(&count, ^{
_sharedFoo = [[Foo alloc] init];
});
return _sharedFoo;
}
EDIT
For more details about working with the dispatch API, see http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html

jlehr
- 15,557
- 5
- 43
- 45