Close Menu
geekfence.comgeekfence.com
    What's Hot

    Fandom Con Ireland’s largest neurodivergent-led gaming convention returns to Belfast

    May 10, 2026

    The Case for AI Tool Registries – O’Reilly

    May 10, 2026

    Best Executive Programs to Build AI Leadership Across Business, Marketing, and Technology 

    May 10, 2026
    Facebook X (Twitter) Instagram
    • About Us
    • Contact Us
    Facebook Instagram
    geekfence.comgeekfence.com
    • Home
    • UK Tech News
    • AI
    • Big Data
    • Cyber Security
      • Cloud Computing
      • iOS Development
    • IoT
    • Mobile
    • Software
      • Software Development
      • Software Engineering
    • Technology
      • Green Technology
      • Nanotechnology
    • Telecom
    geekfence.comgeekfence.com
    Home»iOS Development»Swift object pool design pattern
    iOS Development

    Swift object pool design pattern

    AdminBy AdminJanuary 3, 2026No Comments3 Mins Read1 Views
    Facebook Twitter Pinterest LinkedIn Telegram Tumblr Email
    Swift object pool design pattern
    Share
    Facebook Twitter LinkedIn Pinterest Email


    12/9/18 3:20 PM
    · 1 min read


    In this quick tutorial I’ll explain & show you how to implement the object pool design pattern using the Swift programming language.

    A generic object pool in Swift

    The object pool pattern is a creational design pattern. The main idea behind it is that first you create a set of objects (a pool), then you acquire & release objects from the pool, instead of constantly creating and releasing them. 👍

    Why? Performance improvements. For example the Dispatch framework uses an object pool pattern to give pre-created queues for the developers, because creating a queue (with an associated thread) is an relatively expensive operation.

    Another use case of the object pool pattern is workers. For example you have to download hundreds of images from the web, but you’d like to download only 5 simultaneously you can do it with a pool of 5 worker objects. Probably it’s going to be a lot cheaper to allocate a small number of workers (that’ll actually do the download task), than create a new one for every single image download request. 🖼

    What about the downsides of this pattern? There are some. For example if you have workers in your pool, they might contain states or sensitive user data. You have to be very careful with them aka. reset everything. Also if you are running in a multi-threaded environment you have to make your pool thread-safe.

    Here is a simple generic thread-safe object pool class:

    import Foundation
    
    class Pool {
    
        private let lockQueue = DispatchQueue(label: "pool.lock.queue")
        private let semaphore: DispatchSemaphore
        private var items = [T]()
    
        init(_ items: [T]) {
            self.semaphore = DispatchSemaphore(value: items.count)
            self.items.reserveCapacity(items.count)
            self.items.append(contentsOf: items)
        }
    
        func acquire() -> T? {
            if self.semaphore.wait(timeout: .distantFuture) == .success, !self.items.isEmpty {
                return self.lockQueue.sync {
                    return self.items.remove(at: 0)
                }
            }
            return nil
        }
    
        func release(_ item: T) {
            self.lockQueue.sync {
                self.items.append(item)
                self.semaphore.signal()
            }
        }
    }
    
    
    let pool = Pool(["a", "b", "c"])
    
    let a = pool.acquire()
    print("\(a ?? "n/a") acquired")
    let b = pool.acquire()
    print("\(b ?? "n/a") acquired")
    let c = pool.acquire()
    print("\(c ?? "n/a") acquired")
    
    DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + .seconds(2)) {
        if let item = b {
            pool.release(item)
        }
    }
    
    print("No more resource in the pool, blocking thread until...")
    let x = pool.acquire()
    print("\(x ?? "n/a") acquired again")
    

    As you can see the implementation is just a few lines. You have the thread safe array of the generic pool items, a dispatch semaphore that’ll block if there are no objects available in the pool, and two methods in order to actually use the object pool.

    In the sample you can see that if there are no more objects left in the pool, the current queue will be blocked until a resource is being freed & ready to use. So watch out & don’t block the main thread accidentally! 😉


    Swift object pool design pattern

    Share this article

    Thank you. 🙏

    Related posts

    Swift object pool design pattern

    11/27/20 3:20 PM
    · 6 min read


    In this article I am going to show you how to implement a basic event processing system for your modular Swift application.

    Swift object pool design pattern

    8/19/18 2:20 PM
    · 4 min read


    Learn the iterator design pattern by using some custom sequences, conforming to the IteratorProtocol from the Swift standard library.

    Swift object pool design pattern

    12/17/18 3:20 PM
    · 4 min read


    Learn how to use lazy properties in Swift to improve performance, avoid optionals or just to make the init process more clean.

    Swift object pool design pattern

    8/12/22 2:20 PM
    · 5 min read


    Beginner’s guide about optics in Swift. Learn how to use lenses and prisms to manipulate objects using a functional approach.



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email

    Related Posts

    Introducing SwiftPorts | Cocoanetics

    May 7, 2026

    Awesome native Xcode extensions – The.Swift.Dev.

    May 6, 2026

    ios – Flutter UI not matching design: top-right badge not properly attached to card border

    May 5, 2026

    Four Green Checkmarks: GitHub CI for macOS, iOS, Linux, and Windows

    May 1, 2026

    Swift enum all values – The.Swift.Dev.

    April 30, 2026

    ios – AppShortcut is shown in Shortcuts app but not in Spotlight

    April 29, 2026
    Top Posts

    Understanding U-Net Architecture in Deep Learning

    November 25, 202539 Views

    Hard-braking events as indicators of road segment crash risk

    January 14, 202627 Views

    Redefining AI efficiency with extreme compression

    March 25, 202626 Views
    Don't Miss

    Fandom Con Ireland’s largest neurodivergent-led gaming convention returns to Belfast

    May 10, 2026

    Fandom Con, one of Northern Ireland’s leading gaming conventions specifically designed for and organised by…

    The Case for AI Tool Registries – O’Reilly

    May 10, 2026

    Best Executive Programs to Build AI Leadership Across Business, Marketing, and Technology 

    May 10, 2026

    Understanding AI Agent Memory Patterns: A Guide with LangGraph

    May 10, 2026
    Stay In Touch
    • Facebook
    • Instagram
    About Us

    At GeekFence, we are a team of tech-enthusiasts, industry watchers and content creators who believe that technology isn’t just about gadgets—it’s about how innovation transforms our lives, work and society. We’ve come together to build a place where readers, thinkers and industry insiders can converge to explore what’s next in tech.

    Our Picks

    Fandom Con Ireland’s largest neurodivergent-led gaming convention returns to Belfast

    May 10, 2026

    The Case for AI Tool Registries – O’Reilly

    May 10, 2026

    Subscribe to Updates

    Please enable JavaScript in your browser to complete this form.
    Loading
    • About Us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • Terms and Conditions
    © 2026 Geekfence.All Rigt Reserved.

    Type above and press Enter to search. Press Esc to cancel.