Assume these are instance methods and -run
is called.
Is the lock on self
released by the time -run
returns?
...
- (void)dangerous {
@synchronized (self) {
[NSException raise:@"foo" format:@"bar"];
}
}
- (void)run {
@try { [self dangerous]; }
@catch (NSException *ignored) {}
}
...
Thread inside the synchronized method is set as the owner of the lock and is in RUNNABLE state. Any thread that attempts to enter the locked method becomes BLOCKED. When thread calls wait it releases the current object lock (it keeps all locks from other objects) and than goes to WAITING state.
The lock can be released as soon as the block it protects is finished which means after the return but before the finalized block. That does not mean that the jvm is not allowed to keep the lock a bit longer if it thinks it will improve performance. When one thread reaches the finally block, it has released the lock.
Yes, that is correct. There can only be one thread at the same time holding a lock on an object. Each object has its own lock. So it lock all synchronized (this) block of that object.
Explanation: It releases all the locks it has If a thread goes to sleep. It doesn't open any locks. One important distinction that has yet to be mentioned is that while sleeping, a Thread does not release the locks it holds, whereas waiting releases the lock on the object on which wait() is called.
The unlock() method is another most common method which is used for releasing the lock. The unlock() method is a public method that returns nothing and takes no parameter. Syntax: public void unlock()
A Synchronized block is a piece of code that can be used to perform synchronization on any specific resource of the method. A Synchronized block is used to lock an object for any shared resource and the scope of a synchronized block is smaller than the synchronized method.
A @synchronized(obj) { code }
block is effectively equivalent to
NSRecursiveLock *lock = objc_fetchLockForObject(obj);
[lock lock];
@try {
code
}
@finally {
[lock unlock];
}
though any particular aspect of this is really just implementation details. But yes, a @synchronized
block is guaranteed to release the lock no matter how control exits the block.
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