First time access to lazy var must be done on one thread only.

I came across a crash caused by reading the same lazy property from many threads before it is initialized. When looking closer I saw several threads actually enter lazy initializer and eventually crash around reference counting.

Xcode paused on the _ = holder.value line, with Thread 11 crashing inside Swift release/deallocation code.

🧪 Reproducing the crash

Use lazy property that creates a reference type (class/array) and make its initialization slow enough for several threads to overlap. Then start 1000 tasks that read the same property at roughly the same time - the shared startTime will force all tasks to wait until same time and then start accessing lazy var together. Also helped putting more pressure on CPU by running this whole crash attempt multiple times in parallel.

final class LazyHolder {
    let id = UUID().uuidString
    lazy var value: [Int] = {
        print("⚠️ Init \(id) on \(Thread.current)")
        return Array(0..<100)
    }()
}

@main
struct LazyCrashApp: App {
    var body: some Scene {
        WindowGroup {
            EmptyView()
                .onAppear {
                    // Start multiple attempts to get CPU under pressure
                    for _ in 1..<10 {
                        Task {
                            runCrashAttempt()
                        }
                    }
                }
        }
    }
}

private func runCrashAttempt() {
    // Repeat multiple rounds until the race becomes visible.
    for _ in 0..<10_000 {
        let holder = LazyHolder()
        let group = DispatchGroup()
        let startTime = DispatchTime.now() + .milliseconds(100)
        
        // Schedule many concurrent reads.
        for _ in 0..<1_000 {
            group.enter()
            
            DispatchQueue.global(qos: .userInteractive).async {
                // Release the reads at roughly the same time.
                while DispatchTime.now() < startTime {}
                
                _ = holder.value
                group.leave()
            }
        }
        
        // Finish this round before starting another one.
        group.wait()
    }
}

🔍 What happened

The print inside the initializer showed that several threads try initialize same lazy var.

Detail

The test did not crash every time. Sometimes it ran for a while. Other times it stopped with EXC_BAD_ACCESS, an invalid free, or a stack trace inside Swift reference counting.

_xzm_xzone_malloc_freelist_outlined

Another crash included:

BUG IN CLIENT OF LIBMALLOC: pointer being freed was not allocated
swift_release_dealloc
RefCounts::doDecrementSlow
LazyHolder.value.getter

The Swift documentation confirms it is not thread-safe

If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property hasn’t yet been initialized, there’s no guarantee that the property will be initialized only once.

Peek inside Swift compiler source confirms there is no synchronization. So multiple threads can go inside, read that storage is empty, create lazy value and then race over storage.

Since there is no synchronization around storage, both threads are modyfing the exact same memory address. Then swift_release is called twice for same instance and when ARC counter tries to go below 0 it crashes.

🐛 Lock inside closure will crash

I’ve tried following, and it didn’t help. Will crash as well. Problem is not the closure. Problem is that internal storage inside lazy var is not synchronized.

final class LazyHolder {
    let id = UUID().uuidString
    let lock = NSRecursiveLock()
    lazy var value: [Int] = {
        lock.lock()
        defer { lock.unlock() }
        print("⚠️ Init \(id) on \(Thread.current)")
        return Array(0..<100)
    }()
}

and later:

        _ = holder.value
...

✅ Lock from outside is OK

What won’t crash is, when we put wrap use of lazy var into lock/actor from outside.

final class LazyHolder {
    let id = UUID().uuidString
    lazy var value: [Int] = {
        print("⚠️ Init \(id) on \(Thread.current)")
        return Array(0..<100)
    }()
    
    let lock = NSRecursiveLock()
    var safeReadValue: [Int] {
        lock.lock()
        defer { lock.unlock() }
        return value
    }
}

and later:

        _ = holder.safeReadValue

...

💡 My rule of thumb

Using lazy var for UI stuff on MainActor

  • → No worries

Using lazy var in model/interactor/…/non-MainActor layer?

  • → Would let be enough?
  • → If not, can I use actor or lock around this lazy var to synchronize access to it?