Skip to content

Commit

Permalink
[Basic] Add a thread-safe lazy method cache wrapper.
Browse files Browse the repository at this point in the history
 - This isn't a particularly efficient implementation (in particular, it takes a
   full lock on every access), but it should be sufficient for our current
   purposes.
  • Loading branch information
ddunbar committed May 23, 2016
1 parent 6e0b776 commit a086f6c
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 0 deletions.
57 changes: 57 additions & 0 deletions Sources/Basic/LazyCache.swift
@@ -0,0 +1,57 @@
/*
This source file is part of the Swift.org open source project
Copyright 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

/// Thread-safe lazily cached methods.
///
/// The `lazy` annotation in Swift does not result in a thread-safe accessor,
/// which can make it an easy source of hard-to-find concurrency races. This
/// class defines a wrapper designed to be used as an alternative for
/// `lazy`. Example usage:
///
/// ```
/// class Foo {
/// var bar: Int { return barCache.getValue(self) }
/// var barCache = LazyCache(someExpensiveMethod)
///
/// func someExpensiveMethod() -> Int { ... }
/// }
/// ```
///
/// See: https://bugs.swift.org/browse/SR-1042
//
// FIXME: This wrapper could benefit from local static variables, in which case
// we could embed the cache object inside the accessor.
public struct LazyCache<Class, T> {
// FIXME: It would be nice to avoid a per-instance lock, but this type isn't
// intended for creating large numbers of instances of. We also really want
// a reader-writer lock or something similar here.
private var lock = Lock()
let body: (Class) -> () -> T
var cachedValue: T? = nil

/// Create a lazy cache from a method value.
public init(_ body: (Class) -> () -> T) {
self.body = body
}

/// Get the cached value, computing it if necessary.
public mutating func getValue(_ instance: Class) -> T {
// FIXME: This is unfortunate, see note w.r.t. the lock.
return lock.withLock {
if let value = cachedValue {
return value
} else {
let result = body(instance)()
cachedValue = result
return result
}
}
}
}
45 changes: 45 additions & 0 deletions Tests/Basic/LazyCacheTests.swift
@@ -0,0 +1,45 @@
/*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

import XCTest

import Basic

class LazyCacheTests: XCTestCase {
func testBasics() {
class Foo {
var numCalls = 0

var bar: Int { return barCache.getValue(self) }
var barCache = LazyCache(someExpensiveMethod)
func someExpensiveMethod() -> Int {
numCalls += 1
return 42
}

}

// FIXME: Make this a more interesting test once we have concurrency primitives.
for _ in 0..<10 {
let foo = Foo()
XCTAssertEqual(foo.numCalls, 0)
for _ in 0..<10 {
XCTAssertEqual(foo.bar, 42)
XCTAssertEqual(foo.numCalls, 1)
}
}
}

static var allTests: [(String, (LazyCacheTests) -> () throws -> Void)] {
return [
("testBasics", testBasics),
]
}
}
1 change: 1 addition & 0 deletions Tests/Basic/XCTestManifests.swift
Expand Up @@ -15,6 +15,7 @@ public func allTests() -> [XCTestCaseEntry] {
return [
testCase(ByteStringTests.allTests),
testCase(JSONTests.allTests),
testCase(LazyCacheTests.allTests),
testCase(LockTests.allTests),
testCase(OptionParserTests.allTests),
testCase(OutputByteStreamTests.allTests),
Expand Down

0 comments on commit a086f6c

Please sign in to comment.