sok / Sok.Buffer / BufferPool
class BufferPool
(source)
Platform and version requirements: Common
In order to avoid garbage collection pressure it is a common practice to pre-allocate objects that are known to be long-living for a later use, Kotlin channels give us a great way to implement a quite straightforward object pool. The pool will allocate all the buffers lazily when needed, this means that the pool will never suspend until reaching the maximum size.
This class is of course thread safe
We need to use a factory lambda to let the developer use a DirectByteBuffer pool on the JVM instead of a HeapByteBuffer one
<init> | BufferPool(maximumNumberOfBuffer: Int , bufferSize: Int , bufferBuilder: (bufferSize: Int ) -> MultiplatformBuffer = { allocMultiplatformBuffer(bufferSize) }) Creates an empty pool that will grow to the given maximum number of buffer if needed |
bufferBuilder | val bufferBuilder: (bufferSize: Int ) -> MultiplatformBuffer lambda called when the pool need to allocate a buffer |
bufferSize | val bufferSize: Int parameter passed to the factory lambda, used to determine the size of the buffer to allocate |
maximumNumberOfBuffer | val maximumNumberOfBuffer: Int maximum number of buffer that the pool will allocate |
freeBuffer | suspend fun freeBuffer(obj: MultiplatformBuffer ): Unit Free the object in order to let another coroutine have it. If you forget to call this method the pool will empty itself and starve, blocking all coroutines calling requestBuffer() |
requestBuffer | suspend fun requestBuffer(): MultiplatformBuffer Fetch a buffer from the pool. If the pool as not reached its maximum size and that the channel si empty we can allocate the buffer instead of suspending. |