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.
There is nothing wrong with returning inside a synchronized block. The lock will be released correctly.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With