iOS Interview - Thread explosion in iOS Programming

April 07, 20242 min read#swift, #concurrency, #ios, #interview

I have recently rewatched an old WWDC video about GCD named: Building Responsive and Efficient Apps with GCD. There is an interesting topic mentioned in this video: Thread explosion.

Normally, iOS engineers rarely encounter this thread explosion issue, especially when using modern APIs such as Swift Concurrency. But understand what thread explosion is, and how to avoid it, could help us to design our app more efficently, which helps improve app performance and avoid dead locks issues.

The problem

In iOS programming, “thread explosion” refers to a situation where an application creates an excessive number of threads, leading to performance issues and potential crashes. This typically occurs when an application spawns new threads without properly managing them or fails to reuse existing threads efficiently.

I’d recommend you to watch the GCD video above to understand more about the low level explanation of thread explosion.

You can also read this great article from SwiftSenpai to see pratical example of code, that could lead to thread explosion.

Thread explosion can also lead to dead lock issue when the thread pool is exhausted and no more thread can be created while waiting for initiated tasks to be executed and finished, so that spawned threads can be released. But if we accidently call dispatch_sync in those initiated tasks, which in turn will try to spawn a new thread and block the current thread, dead lock will ocurr because no thread can release its resource to unblock the others.


The solution

There are multiple ways to avoid thread explosions. The WWDC video gives some suggestions:


If your app supports modern iOS versions, it’s great idea to start adopting modern Swift Concurrency API async/await, which is doing its best effort to avoid such thread explosion situation. To understand more how async/await is managing threads to avoid thread explosion, you can read the article from SwiftSenpai again.

Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist

© An Tran - 2024