Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Sources/WrapModel/WrapModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ open class WrapModel : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
private var contributedLock:WrapModelLock?
private var cacheLock = WrapModelLock()
private var cacheLockLock = WrapModelLock()
private lazy var cachedValues = [String:Any]()
private var cachedValues = [String:Any]()
fileprivate func getCached(forProperty property:AnyWrapProperty) -> Any? {
return lock.reading {
return self.cachedValues[property.keyPath]
Expand Down Expand Up @@ -444,6 +444,7 @@ open class WrapProperty<T> : AnyWrapProperty {
}

private func internalValue() -> T? {
guard let model = self.model else { return nil }
if let cachedValue = model.getCached(forProperty: self) {
if cachedValue is NSNull { return nil }
return cachedValue as? T
Expand All @@ -461,6 +462,7 @@ open class WrapProperty<T> : AnyWrapProperty {
}

private func internalSetValue(_ value: T) {
guard let model = self.model else { return }
assert(model.isMutable, "Attempt to mutate immutable model")
guard model.isMutable else { return }
switch value {
Expand Down
29 changes: 29 additions & 0 deletions Tests/ThreadSafetyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,35 @@ final class ThreadSafetyTests: XCTestCase {
group.wait()
}

// MARK: - Test 6: Concurrent property .value reads on a SHARED instance

/// Races the property `.value` getter path (internalValue -> getCached/setCached) on ONE
/// shared model across many threads. Each property's first read populates `cachedValues`;
/// on master that lazy first-touch is a write on the concurrent read path -> data race.
/// Must be clean after making `cachedValues` non-lazy. This is the browse/Follows crash path.
func testConcurrentPropertyValueReadsSharedInstance() {
let iterations = 1000
let threads = 16
let group = DispatchGroup()

for _ in 0..<iterations {
let model = StressTestModel(data: sampleData, mutable: false) // fresh: cachedValues empty
for _ in 0..<threads {
group.enter()
DispatchQueue.global().async {
_ = model.firstName.value
_ = model.age.value
_ = model.city.value
_ = model.followerCount.value
_ = model.rating.value
_ = model.website.value
group.leave()
}
}
group.wait()
}
}

// MARK: - Performance Tests

/// Single-threaded currentModelData on fresh instances.
Expand Down