What does @synchronized() do as a singleton method in objective C?
It declares a critical section around the code block. In multithreaded code, @synchronized
guarantees that only one thread can be executing that code in the block at any given time.
If you aren't aware of what it does, then your application probably isn't multithreaded, and you probably don't need to use it (especially if the singleton itself isn't thread-safe).
Edit: Adding some more information that wasn't in the original answer from 2011.
The @synchronized
directive prevents multiple threads from entering any region of code that is protected by a @synchronized
directive referring to the same object. The object passed to the @synchronized
directive is the object that is used as the "lock." Two threads can be in the same protected region of code if a different object is used as the lock, and you can also guard two completely different regions of code using the same object as the lock.
Also, if you happen to pass nil
as the lock object, no lock will be taken at all.
From the Apple documentation here and here:
The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time.
The documentation provides a wealth of information on this subject. It's worth taking the time to read through it, especially given that you've been using it without knowing what it's doing.