Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are @synchronized blocks guaranteed to release their locks?

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) {}
}
...
like image 880
Todd Ditchendorf Avatar asked Oct 12 '11 05:10

Todd Ditchendorf


People also ask

How do you release a lock on a synchronized block?

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.

When leaving a synchronized block one has to make sure the lock is released by always using a try finally construct?

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.

Does synchronized block acquire a lock before its execution explain your answer?

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.

When thread goes to sleep does it hold the lock?

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.

Which method releases the lock?

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()

What is the purpose of synchronized block?

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.


1 Answers

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.

like image 87
Lily Ballard Avatar answered Sep 25 '22 15:09

Lily Ballard