1 46 47 51 package org.mr.core.util.byteable; 52 53 import java.nio.ByteBuffer ; 54 55 57 58 59 import org.mr.core.util.SynchronizedQueue; 60 61 62 69 public class IncomingByteBufferPool implements ByteBufferFactory { 70 71 72 static final int SMALL_SIZE_BUFFER = 2048; 73 static final int MEDIUM_SIZE_BUFFER = 6120; 74 static final int LARGE_SIZE_BUFFER = 10240; 75 76 private static IncomingByteBufferPool instance = new IncomingByteBufferPool(); 77 private SynchronizedQueue small = new SynchronizedQueue(); 78 private SynchronizedQueue medium = new SynchronizedQueue(); 79 private SynchronizedQueue large = new SynchronizedQueue(); 80 81 82 83 public final static IncomingByteBufferPool getInstance(){ 84 return instance; 85 } 87 88 91 private IncomingByteBufferPool() { 92 93 for (int i = 0; i < ByteBufferPool.numInSmallPool; i++) { 94 small.enqueue(ByteBuffer.allocate(ByteBufferPool.SMALL_SIZE_BUFFER)); 95 } 97 for (int i = 0; i < ByteBufferPool.numInMediumPool; i++) { 98 medium.enqueue(ByteBuffer.allocate(ByteBufferPool.MEDIUM_SIZE_BUFFER)); 99 } 101 for (int i = 0; i < ByteBufferPool.numInLargePool; i++) { 102 large.enqueue(ByteBuffer.allocate(ByteBufferPool.LARGE_SIZE_BUFFER)); 103 } } 106 107 public final ByteBuffer getBuffer(int size){ 108 109 ByteBuffer result = null; 110 if(size <= ByteBufferPool.SMALL_SIZE_BUFFER){ 111 result= (ByteBuffer )small.dequeue(); 112 }else if(size <= ByteBufferPool.MEDIUM_SIZE_BUFFER){ 113 result= (ByteBuffer )medium.dequeue(); 114 }else if(size <= ByteBufferPool.LARGE_SIZE_BUFFER){ 115 result= (ByteBuffer )large.dequeue(); 116 }else{ 117 result= ByteBuffer.allocate(size); 119 } 120 121 result.limit(size); 122 return result; 123 } 125 126 public final void release(ByteBuffer buffer){ 127 128 if(buffer==null) 130 return; 131 132 buffer.position(0); 133 buffer.limit(buffer.capacity()); 134 buffer.mark(); 135 int size = buffer.capacity(); 136 137 if(size == ByteBufferPool.SMALL_SIZE_BUFFER && small.size() < ByteBufferPool.numInSmallPool) 138 small.enqueue(buffer); 139 else if(size == ByteBufferPool.MEDIUM_SIZE_BUFFER) 140 medium.enqueue(buffer); 141 else if(size == ByteBufferPool.LARGE_SIZE_BUFFER) 142 large.enqueue(buffer); 143 } 145 146 149 public int getSmallBufferSize() { 150 return ByteBufferPool.SMALL_SIZE_BUFFER; 152 } 153 } 154 | Popular Tags |