Class
class ObjectPool<T> where T <: Object
public class ObjectPool<T> where T <: Object
Description: Provides a concurrent-secure object cache type, which can store objects that have been allocated memory but are not in use.
Notes:
- When an object is not needed, it can be stored in ObjectPool, and when the object is needed, it can be obtained from ObjectPool.
- Objects stored in ObjectPool must be of the same type.
- Before the lifecycle of an ObjectPool object ends, objects stored in the ObjectPool object are not released.
Example:
import std.objectpool.*
class City {
var id: Int64 = 0
var name: String = ""
}
func resetCity(c: City): City {
let city = c
city.id = 0
city.name = ""
return city
}
main() {
let cityPool = ObjectPool({ => City()}, resetFunc: resetCity)
let cityA = cityPool.get()
cityA.id = 30
cityA.name = "A"
println("id: ${cityA.id}, name: ${cityA.name}")
cityPool.put(cityA)
}
Running result:
id: 30, name: A
init(() -> T, Option<(T) -> T>)
public init(newFunc: () -> T, resetFunc!: Option<(T) -> T> = None)
Description: Creates a new ObjectPool object.
Parameters:
- newFunc: () ->T: When the get method is called, if the method fails to obtain an object from ObjectPool, the newFn function is called to create a new object. The newFunc function must ensure concurrency security.
- resetFunc!: Option<(T) ->T>: When the get method is called, the resetFunc function is called to reset the object status. If resetFunc is None, the object status is not reset. The resetFunc must ensure concurrency security.
func get()
public func get(): T
Description: Attempts to obtain an object from ObjectPool. If obtaining an object from ObjectPool fails, the newFunc is called to create a new object and return it. If an object obtained using the get method is no longer needed, it should be returned to ObjectPool using the put method.
Returns:
- T: object obtained from ObjectPool or created by calling newFunc
func put(T)
public func put(item: T): Unit
Description: Attempts to place an object into ObjectPool but does not guarantee that the object is added to ObjectPool. After put is called on an object, no further operations should be performed on the object, as it may lead to unexpected issues.
Parameters:
- item: T: object to be put into ObjectPool