22

I read in this article that in Java, nested synchronised blocks are allowed. I know that Objective-C's synchronised blocks look a lot like Java's. So I wonder: Are nested blocks allowed in Objective-C?

I also have a side question: Is there a practical limit on recursive blocks?

Thank you for your speedy answer!

Community
  • 1
  • 1
Constantino Tsarouhas
  • 6,846
  • 6
  • 43
  • 54

1 Answers1

28

Yes, they are. From the docs (now retired):

The Objective-C synchronization feature supports recursive and reentrant code. A thread can use a single semaphore several times in a recursive manner; other threads are blocked from using it until the thread releases all the locks obtained with it; that is, every @synchronized() block is exited normally or through an exception.

For a discussion of performance with this and other methods of synchronization/locking, see here.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • Thanks @bkbeachlabs. I've updated my links to point to old/archived versions of what they used to be. I'm not sure where you can find this "`@synchronized` is reentrant" guarantee in the current docs. – jtbandes Aug 13 '15 at 16:49
  • 1
    It can now be found here: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocThreading.html#//apple_ref/doc/uid/TP30001163-CH19-SW1 "The Objective-C synchronization feature supports recursive and reentrant code. A thread can use a single semaphore several times in a recursive manner; other threads are blocked from using it until the thread releases all the locks obtained with it; that is, every @synchronized() block is exited normally or through an exception." – MrHappyAsthma Oct 21 '19 at 20:59