Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning from method inside a @synchronized block

I'd just like to know if it's advised to return from a method within a @synchronized block? For example:

- (id)test {
   @synchronized(self) {
      if (a) return @"A";
      else return @"B";
   }
}

As opposed to:

- (id)test {
   NSString *value;
   @synchronized(self) {
      if (a) value = @"A";
      else value = @"B";
   }
   return value;
}

This sample is rather simplistic, but sometimes in a complex method it would make things simpler to be able to return from within a @synchronized block.

like image 745
Michael Waterfall Avatar asked Apr 24 '10 12:04

Michael Waterfall


People also ask

Can we return from synchronized block?

There is nothing wrong with returning inside a synchronized block. The lock will be released correctly.

How synchronization works internally in Java?

This synchronization is implemented in Java with a concept called monitors. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.

What does synchronized method do?

Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.

What is intrinsic locking?

An intrinsic lock (aka monitor lock) is an implicit internal entity associated with each instance of objects. The intrinsic lock enforces exclusive access to an object's state. Here 'access to an object' refers to an instance method call.


1 Answers

It's fine. @synchronized is aware of the return statement.

(Ref: http://www.thaesofereode.info/clocFAQ/#sync-advs) - dead link
(Ref: http://nextstep.sdf-eu.org/clocFAQ/#sync-advs) - this link reference above dead one and may not be up to date as its header says

like image 169
kennytm Avatar answered Oct 21 '22 08:10

kennytm