Skip to content

Commit

Permalink
Actor BackgroundDeallocationQueue (#419)
Browse files Browse the repository at this point in the history
  • Loading branch information
muukii authored Sep 22, 2023
1 parent 89cb2cd commit 35621d2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 20 deletions.
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

0 comments on commit 35621d2

Please sign in to comment.