What
are singletons? — Singleton is design patterns which says that there
should be only one instance of the class for the lifetime of the
application.
One the best example of Singleton is AppDelegate.
How to write a singleton class ?
class DefaultDict{ private var dict:[String:Any] = [:] public static let sharedManager = DefaultDict() private init(){ } public func set(value:Any,key:String){ dict[key] = value } public func object(key:String) -> Any?{ dict[key] } public func reset(){ dict.removeAll() } }
Testing singleton class under concurrent circumstances. We are going to write an example where we will set values in dict
from various threads and even try to access some with different
threads. When we do this we will encounter a crash. If you look closely
it will be because of race condition and the crash will be on line set(value:Any,key:String).
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let count = 100 for index in 0..<count{ DefaultDict.sharedManager.set(value: index, key: String(index)) } DispatchQueue.concurrentPerform(iterations:count) { (index) in if let n = DefaultDict.sharedManager.object(key: String(index)) as? Int{ print(n) } } DefaultDict.sharedManager.reset() DispatchQueue.concurrentPerform(iterations:count) { (index) in DefaultDict.sharedManager.set(value:index,key:String(index)) } } }
You can create a thread safe singleton using DispatchQueue. We will
create a serial queue and add a sync method to set and get value. Below
is the code you can achieve thread safe singleton class.
class DefaultDict{ private let serialQueue = DispatchQueue(label: "serialQueue") private var dict:[String:Any] = [:] public static let sharedManager = DefaultDict() private init(){ } public func set(value:Any,key:String){ serialQueue.sync{ dict[key] = value } } public func object(key:String) -> Any?{ var result:Any? serialQueue.sync{ result = dict[key] } return result } public func reset(){ dict.removeAll() } }
It will write an another blog where we can improve the performance using dispatch barrier.
That’s all for now.
You can connect me on —
Comments
Post a Comment