Swift object pool design sample

Swift object pool design sample



· 1 min learn


On this fast tutorial I will clarify & present you learn how to implement the item pool design sample utilizing the Swift programming language.

A generic object pool in Swift

The object pool sample is a creational design sample. The principle thought behind it’s that first you create a set of objects (a pool), then you definitely purchase & launch objects from the pool, as an alternative of continually creating and releasing them. 👍

Why? Efficiency enhancements. For instance the Dispatch framework makes use of an object pool sample to present pre-created queues for the builders, as a result of making a queue (with an related thread) is an comparatively costly operation.

One other use case of the object pool sample is staff. For instance it’s important to obtain lots of of photos from the net, however you’d prefer to obtain solely 5 concurrently you are able to do it with a pool of 5 employee objects. In all probability it’s going to be so much cheaper to allocate a small variety of staff (that’ll really do the obtain process), than create a brand new one for each single picture obtain request. 🖼

What concerning the downsides of this sample? There are some. For instance when you have staff in your pool, they could comprise states or delicate consumer knowledge. It’s important to be very cautious with them aka. reset every thing. Additionally if you’re operating in a multi-threaded setting it’s important to make your pool thread-safe.

Right here is an easy generic thread-safe object pool class:

import Basis

class Pool<T> {

    personal let lockQueue = DispatchQueue(label: "pool.lock.queue")
    personal let semaphore: DispatchSemaphore
    personal var gadgets = [T]()

    init(_ gadgets: [T]) {
        self.semaphore = DispatchSemaphore(worth: gadgets.rely)
        self.gadgets.reserveCapacity(gadgets.rely)
        self.gadgets.append(contentsOf: gadgets)
    }

    func purchase() -> T? {
        if self.semaphore.wait(timeout: .distantFuture) == .success, !self.gadgets.isEmpty {
            return self.lockQueue.sync {
                return self.gadgets.take away(at: 0)
            }
        }
        return nil
    }

    func launch(_ merchandise: T) {
        self.lockQueue.sync {
            self.gadgets.append(merchandise)
            self.semaphore.sign()
        }
    }
}


let pool = Pool<String>(["a", "b", "c"])

let a = pool.purchase()
print("(a ?? "n/a") acquired")
let b = pool.purchase()
print("(b ?? "n/a") acquired")
let c = pool.purchase()
print("(c ?? "n/a") acquired")

DispatchQueue.international(qos: .default).asyncAfter(deadline: .now() + .seconds(2)) {
    if let merchandise = b {
        pool.launch(merchandise)
    }
}

print("No extra useful resource within the pool, blocking thread till...")
let x = pool.purchase()
print("(x ?? "n/a") acquired once more")

As you’ll be able to see the implementation is just some traces. You will have the thread protected array of the generic pool gadgets, a dispatch semaphore that’ll block if there aren’t any objects accessible within the pool, and two strategies in an effort to really use the item pool.

Within the pattern you’ll be able to see that if there aren’t any extra objects left within the pool, the present queue can be blocked till a useful resource is being freed & prepared to make use of. So be careful & don’t block the principle thread by accident! 😉

Associated posts


· 5 min learn


On this article I’m going to point out you learn how to implement a primary occasion processing system on your modular Swift software.


· 4 min learn


Study the iterator design sample through the use of some customized sequences, conforming to the IteratorProtocol from the Swift commonplace library.


· 4 min learn


Discover ways to use lazy properties in Swift to enhance efficiency, keep away from optionals or simply to make the init course of extra clear.


· 5 min learn


Newbie’s information about optics in Swift. Discover ways to use lenses and prisms to control objects utilizing a useful strategy.

author avatar
roosho Senior Engineer (Technical Services)
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog. 
rooshohttps://www.roosho.com
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog. 

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here


Latest Articles

author avatar
roosho Senior Engineer (Technical Services)
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog.