                     currentlyInstantiating[id] = instantiation
                     return instantiation
                 }
-            }
+            }()
             
             if instantiation.thread != Thread.current {
                 Meow.log("Waiting for instance from other thread")

            }
        }
        
        /// The amount of objects to keep strong references to
        public var strongReferenceAmount = 0
        
        private var strongReferences = [BaseModel]()
        
        /// The queue used to prevent crashes in mutations
        private let objectPoolMutationQueue = DispatchQueue(label: "org.openkitten.meow.objectPool", qos: .userInteractive)
        
        fileprivate init() {
            // Save the database contents before exiting

            
            Meow.log("Unpooling \(instance)")
            
            storage[instance._id] = nil
            
            // remove if invalidated to free up memory:
            invalidatedObjectIds.remove(instance._id)
        }
        
        /// The amount of pooled objects
        public var count: Int {
            objectPoolMutationLock.lock()
            defer { objectPoolMutationLock.unlock() }
            
            self.clean()
            return storage.count
        }
        
        /// Removes deallocated entries from the pool
        @discardableResult
        public func clean() -> Int {
            objectPoolMutationLock.lock()
            defer { objectPoolMutationLock.unlock() }
            
            var cleanedCount = 0
            
            for (id, val) in storage {
                if val.instance.value == nil {
                    storage[id] = nil
                    cleanedCount += 1
                }
            }
            
            return cleanedCount
        }
        
        /// Handles automatically saving models so they don't get lost when the server randomly crashes/shuts down
        fileprivate func maintenance() {
            objectPoolMutationLock.lock()
            let oldObjects = storage.filter({ $0.value.instantiation.timeIntervalSinceNow < -(minimumAutosaveAge) })
            objectPoolMutationLock.unlock()
            
            for (_, val) in oldObjects {
//                Meow.maintenanceQueue.async {
                    do {
                        try (val.instance.value as? BaseModel)?.save()
                    } catch {
                        Meow.log("❗ Error while performing autosave")
                        Meow.log(error)
                        assertionFailure("\(error)")
                    }
//                }
            }
        }
    }
