Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Actor BackgroundDeallocationQueue #419

Merged
merged 3 commits into from
Sep 22, 2023
Merged
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
33 changes: 15 additions & 18 deletions Sources/Verge/Library/BackgroundDeallocationQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,43 +20,40 @@
// THE SOFTWARE.

import Foundation
import Collections

final class BackgroundDeallocationQueue {
actor BackgroundDeallocationQueue {

private let queue = DispatchQueue.init(label: "org.VergeGroup.deallocQueue", qos: .background)

private var buffer: ContiguousArray<Unmanaged<AnyObject>> = .init()

private let lock = NSLock()
private var buffer: Deque<Unmanaged<AnyObject>> = .init()

func releaseObjectInBackground(object: AnyObject) {

let innerCurrentRef = Unmanaged.passRetained(object)

lock.lock()

let isFirstEntry = buffer.isEmpty
buffer.append(innerCurrentRef)

lock.unlock()

if isFirstEntry {
queue.asyncAfter(deadline: .now() + 0.1) {
self.drain()
Task {
// accumulate objects to dealloc for batching
try? await Task.sleep(nanoseconds: 1_000_000)
await self.drain()
}
}
}

func drain() {
func drain() async {

lock.lock()
let block = buffer
buffer = .init()
lock.unlock()
guard buffer.isEmpty == false else {
return
}

for pointer in block {
while let pointer = buffer.popFirst() {
pointer.release()
await Task.yield()
}

await drain()

}
}
6 changes: 4 additions & 2 deletions Sources/Verge/Store/Changes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import Foundation
#if !COCOAPODS
#endif

private let changesDeallocationQueue = BackgroundDeallocationQueue()
private let _shared_changesDeallocationQueue = BackgroundDeallocationQueue()

public protocol AnyChangesType: AnyObject, Sendable {

Expand Down Expand Up @@ -169,7 +169,9 @@ public final class Changes<Value: Equatable>: @unchecked Sendable, ChangesType,
deinit {
vergeSignpostEvent("Changes.deinit", label: "\(type(of: self))")

changesDeallocationQueue.releaseObjectInBackground(object: innerBox)
Task { [innerBox] in
await _shared_changesDeallocationQueue.releaseObjectInBackground(object: innerBox)
}
}

@inline(__always)
Expand Down