Why do we pass self in @synchronized block?

Advaith picture Advaith · Jul 26, 2012 · Viewed 7.8k times · Source

I guess @synchronized blocks are not object dependent but thread dependent...right? In that case why do we pass self?

Answer

@synchronized is a construct provided by the language to create synchronized scopes. As it would be highly inefficient to use a simple global shared mutex, and thus serializing every single @synchronized scope in the application, the language allows us to specify a synchronization point.

Then it's up to the developer(s) to decide which synchronization points are appropriate for the task.

On an instance method, using self is common: the instance is the synchronization point. The @synchronized(self) scope can be called on any number of instances, but only once for a given instance. Every @synchronized(self) scope will be serialized for a given instance.

Of course, you are free to use another synchronization point if you want to do so. You can use the class (@synchronized(self.class)) or anything else that suits your needs.