Always an Easier Way

Previously in Avoiding an Objective-C Pitfall #1 I discussed a more stable way of creating singletons in Objective-C.  As with all things in the world of Apple there’s always an easier way and that way comes to us via two very powerful yet unnoticed (in the Windows and Linux communities at least) APIs that Apple has contributed to the development community.  The first is a library that Apple developed to make multithreading safer and easier in a way that no other library ever has.  It’s called Grand Central Dispatch (a nod to New York City’s famous Grand Central Station) that reintroduces threads in terms of dispatch queues.  If you have never heard of it I highly recommend getting to know it.  Versions of it also exist for FreeBSD, Linux, and Windows.

The second is actually an extension to the C language that Apple submitted that is a default part of the clang/llvm C/C++/Objective-C compiler (the default compiler for Apple) called Blocks. If you’ve ever worked with closures in other languages such as Javascript then Blocks will instantly be familiar to you.  In fact, from here on out I will refer to these code sections as closures.  As with GCD, Blocks are supported on FreeBSD, Linux, and Windows.

So let’s get right into how all of this makes things easier in the realm of singletons. The first thing I recommend doing is creating a simple function to return a shared instance of a serial dispatch queue.  Yes, a singleton! 🧐

Screen Shot 2018-09-10 at 10.53.53 AM

Here we see things in action right off the bat. We use Grand Central Dispatch’s dispatch_once(…) function to create a single serial dispatch queue. Notice right away that there are no locks or @synchronized(){} blocks anywhere to be found.  That’s because the contract for the dispatch_once(…) function says that in the event of multiple threads calling it at once, only one thread will execute.  All other threads will be blocked until the currently executing thread completes.  And, in this case, the variable _serialQOnce acts as a predicate that will keep the closure from being executed more than once.  Initialized to zero, dispatch_once(…) will set that variable to a non-zero value upon completion. The body of the closure performs the actual creation of the singleton.

The reason we’re doing this first is because serial dispatch queues are extremely handy and this gives you a single, static queue that isn’t one of the system “global queues” that could become very busy.  The one produced by this function will be just for your application and your application only.

So let’s move on to using a serial dispatch queue to create an improved singleton factory for a class.  Serial dispatch queues have a unique property in that blocks placed on them are executed sequentially with respect to each other but asynchronously with respect to other queues (even other serial queues) and threads.  Boiled down this simply means that each item pulled off the queue (in FIFO order) is allowed to fully complete executing before the next item is pulled off the queue.  This is in contrast to a concurrent queue in which items are pulled off, started executing, and then the next item is pulled off and started executing without waiting for the previous item(s) to complete.

Think of it this way, suppose you have a corn maze that you let children run through.  Now imagine a line of children (your queue) waiting to enter the maze.  In a concurrent queue you would allow the children to enter the maze one at a time but you don’t wait for that child to finish the maze before you let the next child into the maze. Perhaps you separate them by only one second. The end result is that, depending on the child’s abilities, such as how fast they can run, the first child into the maze may not be the first one out of the maze.  In fact the first child in might even be the very last one out!

In a sequential queue however, you still have your corn maze and your line of children (your queue) but this time as you let a child in you wait for them to complete the maze before you let the next child in.  This has the effect of guaranteeing that the first child in is the first child out and, by extension, the last child in is the last child out.  But it also has the effect that each child is alone in the maze and able to complete it entirely at their own pace – they’re not going to get run over by another child.  This is the effect that we are going to take advantage of.

So let’s look at the code…

Screen Shot 2018-09-10 at 11.36.36 AM

It looks almost the same except that the body of code that use to be inside a @synchronized(){} block is now inside a closure that is executed on a serial dispatch queue.  The dispatch_sync(…) function (the “sync” has nothing to do with the fact that we’re using a serial queue) will wait until the closure provided has completed executing before it returns. This guarantees that the _instance variable will be populated when the function completes. The “__block” storage modifier on the _instance variable simply allows it to be modified from inside the closure.  Also any concurrent calls to this method are guaranteed to happen sequentially so that two instances of the same class are not created at the same time.

So why is this better? Well, that depends on your point of view I suppose.  But for me it eliminates the @synchronized(){} construct that is known to have a rather high time cost.  Also I feel it looks, overall, a little more elegant.

Leave a Reply