Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory

class ByteArrayBufferPool(
private val pool: ConcurrentLinkedQueue<ByteArrayBuffer>,
private val bufferSize: Int = Constants.Codec.DEFAULT_BUFFER_SIZE,
) {
companion object {
private val logger = LoggerFactory.getLogger(ByteArrayBufferPool::class.java)
Expand All @@ -31,7 +32,7 @@ class ByteArrayBufferPool(
pool.add(ByteArrayBuffer(bufferSize))
}

return ByteArrayBufferPool(pool)
return ByteArrayBufferPool(pool, bufferSize)
}

@JvmStatic
Expand All @@ -58,7 +59,7 @@ class ByteArrayBufferPool(
return value
}

fun acquire(): ByteArrayBuffer = pool.poll()
fun acquire(): ByteArrayBuffer = pool.poll() ?: ByteArrayBuffer(bufferSize)

fun release(buffer: ByteArrayBuffer) {
pool.add(buffer)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.kakao.actionbase.core.codec

import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNotSame

import org.junit.jupiter.api.Test

class ByteArrayBufferPoolTest {
companion object {
private const val BUFFER_SIZE = 64
}

@Test
fun `use should encode with a new buffer when the pool is exhausted`() {
val pool = ByteArrayBufferPool.create(poolSize = 1, bufferSize = BUFFER_SIZE)

val outer =
pool.use { pooled ->
pooled.putValue(1)
val inner =
pool.use { allocated ->
assertNotSame(pooled, allocated)
allocated.putValue(2).toByteArray()
}
assertContentEquals(unpooled(2), inner)
pooled.toByteArray()
}

assertContentEquals(unpooled(1), outer)
}

@Test
fun `acquire should allocate a buffer of the pool's buffer size when the pool is exhausted`() {
val pool = ByteArrayBufferPool.create(poolSize = 1, bufferSize = BUFFER_SIZE)
val pooled = pool.acquire()

val allocated = pool.acquire()

assertNotSame(pooled, allocated)
assertEquals(BUFFER_SIZE, allocated.length)
}

private fun unpooled(value: Int): ByteArray = ByteArray(BUFFER_SIZE).buffer().putValue(value).toByteArray()
}
Loading