Skip to content

Commit 9471103

Browse files
authored
Refactor Cache locking mechanism to use NSRecursiveLock for improved thread safety and prevent deadlocks. Added comprehensive thread safety tests to validate the fix and ensure no new locking issues are introduced. (#22)
* Refactor Cache locking mechanism to use NSRecursiveLock for improved thread safety and prevent deadlocks. Added comprehensive thread safety tests to validate the fix and ensure no new locking issues are introduced. * Refactor ThreadSafetyTests to improve clarity and maintain compatibility with Windows. Added type annotations for ComposableCache and AnyCacheable instances, and wrapped tests in conditional compilation to exclude them on Windows. * Add cache initialization in thread safety tests to avoid redundant instantiation. This change enhances test clarity and performance by reusing the cache instance across multiple operations. * Enhance thread safety tests by refining cache initialization and improving test clarity. Updated comments to reflect changes in locking mechanisms and added new test scenarios to validate cache behavior under high contention and mixed operations.
1 parent c0e89d0 commit 9471103

File tree

2 files changed

+548
-3
lines changed

2 files changed

+548
-3
lines changed

Sources/Cache/Cache/Cache.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ import Foundation
1616
open class Cache<Key: Hashable, Value>: Cacheable, @unchecked Sendable {
1717

1818
/// Lock to synchronize the access to the cache dictionary.
19-
fileprivate var lock: NSLock
19+
/// Using NSRecursiveLock to prevent re-entrant lock deadlocks with @Published property wrapper
20+
fileprivate var lock: NSRecursiveLock
2021

2122
#if os(Linux) || os(Windows)
2223
fileprivate var cache: [Key: Value] = [:]
@@ -31,7 +32,7 @@ open class Cache<Key: Hashable, Value>: Cacheable, @unchecked Sendable {
3132
- Parameter initialValues: An optional dictionary of initial key-value pairs.
3233
*/
3334
required public init(initialValues: [Key: Value] = [:]) {
34-
lock = NSLock()
35+
lock = NSRecursiveLock()
3536
cache = initialValues
3637
}
3738

0 commit comments

Comments
 (0)