Pages

Showing posts with label Singletons. Show all posts
Showing posts with label Singletons. Show all posts

dispatch_once() in extream depth

        In this post I will be discussing all about dispatch_once(), why to use it?, when to use it?, what exactly it does? and what is happening under the hood?
        dispatch_once() behaves as it is specified by it's name, whatever it does it is once and only once. And that's what makes it very interesting API of all in GCD. It's syntactical form in  implemented below, it takes two argument, first is flag that takes care of the once thing and second is the task that you want to perform only once.

         static var flag: dispatch_once_t = 0
         dispatch_once(&static.flag) {
                    //perform some task here.
         } 

        It is a very best and suitable API for lazily initializing shared state of any type kind of dictionary, array or anything. Also it is much faster API than locks which do same thing.
        Now a million dollar thing this API is kind of a swordsman without it's sword in Single-threaded environment and can be replace by simple if-else block. We use it and Apple documentation recommends it to use in multi-threaded environment because of it's ability of being Thread-Safe, means if multiple threads are executing same shared code then it will perform a kind of lock on block/task thread is executing and won't leave until thread unlock it, meanwhile all other threads have to wail for that lock to relinquished.
 

GCD's dispatch_once() and Singleton Class

        Singleton is an object which is restricted to be the only instance of its class, I believe you guys are familiar with this definition. In this tutorial you will learn why and not to use it. What are it's advantages and disadvantages. And what happens when you use it with GCD's dispatch_once() function.
        
Advantages of using Singletons: 

1.) A singleton object is created only once and once created it will available through out you program/app. And it will let you access all objects defined in this class as they are global from any other class.
2.) If any class represents an entity which inherently Singular then having a single instance of a class is most appropriate.
3.) Singletons are most appropriate in situations when you have a lot of common functionality that will be used frequently, you can define that functionality at only one place.
4.) Resources allocated in Singleton are not allocated until they are needed means they are initialized Lazily.