1 46 50 package org.mr.core.util.byteable; 51 52 import java.nio.ByteBuffer ; 53 54 56 57 58 import org.mr.core.util.SynchronizedQueue; 59 60 61 69 public class NetOutByteBufferPool { 70 static final int SMALL_SIZE_BUFFER = 2048; 71 static final int MEDIUM_SIZE_BUFFER = 6120; 72 static final int LARGE_SIZE_BUFFER = 10240; 73 74 private static NetOutByteBufferPool instance = new NetOutByteBufferPool(); 75 private SynchronizedQueue small = new SynchronizedQueue(); 76 private SynchronizedQueue medium = new SynchronizedQueue(); 77 private SynchronizedQueue large = new SynchronizedQueue(); 78 79 80 81 public final static NetOutByteBufferPool getInstance(){ 82 return instance; 83 } 85 86 89 private NetOutByteBufferPool() { 90 91 for (int i = 0; i < ByteBufferPool.numInSmallPool; i++) { 92 small.enqueue(ByteBuffer.allocate(ByteBufferPool.SMALL_SIZE_BUFFER)); 93 } 95 for (int i = 0; i < ByteBufferPool.numInMediumPool; i++) { 96 medium.enqueue(ByteBuffer.allocate(ByteBufferPool.MEDIUM_SIZE_BUFFER)); 97 } 99 for (int i = 0; i < ByteBufferPool.numInLargePool; i++) { 100 large.enqueue(ByteBuffer.allocate(ByteBufferPool.LARGE_SIZE_BUFFER)); 101 } } 104 105 public final ByteBuffer getBuffer(int size){ 106 107 ByteBuffer result = null; 108 if(size <= ByteBufferPool.SMALL_SIZE_BUFFER){ 109 result= (ByteBuffer )small.dequeue(); 110 }else if(size <= ByteBufferPool.MEDIUM_SIZE_BUFFER){ 111 result= (ByteBuffer )medium.dequeue(); 112 }else if(size <= ByteBufferPool.LARGE_SIZE_BUFFER){ 113 result= (ByteBuffer )large.dequeue(); 114 }else{ 115 result= ByteBuffer.allocate(size); 117 } 118 119 result.limit(size); 120 return result; 121 } 123 124 public final void release(ByteBuffer buffer){ 125 126 if(buffer==null) 128 return; 129 130 buffer.position(0); 131 buffer.limit(buffer.capacity()); 132 buffer.mark(); 133 int size = buffer.capacity(); 134 135 if(size == ByteBufferPool.SMALL_SIZE_BUFFER && small.size() < ByteBufferPool.numInSmallPool) 136 small.enqueue(buffer); 137 else if(size == ByteBufferPool.MEDIUM_SIZE_BUFFER) 138 medium.enqueue(buffer); 139 else if(size == ByteBufferPool.LARGE_SIZE_BUFFER) 140 large.enqueue(buffer); 141 }} 143 144 | Popular Tags |