Small optimizations on DirectBufferPool

This commit is contained in:
Trustin Lee 2010-01-27 06:55:10 +00:00
parent c4a230a582
commit 966004332b

View File

@ -27,15 +27,13 @@ import org.jboss.netty.buffer.ChannelBuffer;
*/ */
final class DirectBufferPool { final class DirectBufferPool {
private final SoftReference<ByteBuffer>[] pool; private static final int POOL_SIZE = 4;
DirectBufferPool() {
this(4);
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
DirectBufferPool(int poolSize) { private final SoftReference<ByteBuffer>[] pool = new SoftReference[POOL_SIZE];
pool = new SoftReference[poolSize];
DirectBufferPool() {
super();
} }
final ByteBuffer acquire(ChannelBuffer src) { final ByteBuffer acquire(ChannelBuffer src) {
@ -46,7 +44,7 @@ final class DirectBufferPool {
} }
private final ByteBuffer acquire(int size) { private final ByteBuffer acquire(int size) {
for (int i = 0; i < pool.length; i ++) { for (int i = 0; i < POOL_SIZE; i ++) {
SoftReference<ByteBuffer> ref = pool[i]; SoftReference<ByteBuffer> ref = pool[i];
if (ref == null) { if (ref == null) {
continue; continue;
@ -75,11 +73,7 @@ final class DirectBufferPool {
} }
final void release(ByteBuffer buffer) { final void release(ByteBuffer buffer) {
if (buffer == null) { for (int i = 0; i < POOL_SIZE; i ++) {
return;
}
for (int i = 0; i < pool.length; i ++) {
SoftReference<ByteBuffer> ref = pool[i]; SoftReference<ByteBuffer> ref = pool[i];
if (ref == null || ref.get() == null) { if (ref == null || ref.get() == null) {
pool[i] = new SoftReference<ByteBuffer>(buffer); pool[i] = new SoftReference<ByteBuffer>(buffer);
@ -88,7 +82,8 @@ final class DirectBufferPool {
} }
// pool is full - replace one // pool is full - replace one
for (int i = 0; i< pool.length; i ++) { final int capacity = buffer.capacity();
for (int i = 0; i< POOL_SIZE; i ++) {
SoftReference<ByteBuffer> ref = pool[i]; SoftReference<ByteBuffer> ref = pool[i];
ByteBuffer pooled = ref.get(); ByteBuffer pooled = ref.get();
if (pooled == null) { if (pooled == null) {
@ -96,14 +91,14 @@ final class DirectBufferPool {
continue; continue;
} }
if (pooled.capacity() < buffer.capacity()) { if (pooled.capacity() < capacity) {
pool[i] = new SoftReference<ByteBuffer>(buffer); pool[i] = new SoftReference<ByteBuffer>(buffer);
return; return;
} }
} }
} }
static final int normalizeCapacity(int capacity) { private static final int normalizeCapacity(int capacity) {
// Normalize to multiple of 4096. // Normalize to multiple of 4096.
// Strictly speaking, 4096 should be normalized to 4096, // Strictly speaking, 4096 should be normalized to 4096,
// but it becomes 8192 to keep the calculation simplistic. // but it becomes 8192 to keep the calculation simplistic.