1 46 50 package org.mr.core.util.byteable; 51 52 import java.nio.ByteBuffer ; 53 54 55 56 import org.mr.core.util.SynchronizedQueue; 57 58 59 68 public class ByteBufferPool implements ByteBufferFactory{ 69 70 public static int numInSmallPool = 50; 71 public static int numInMediumPool = 2000; 72 public static int numInLargePool = 10; 73 74 public static final int SMALL_SIZE_BUFFER = 2048; 75 public static final int MEDIUM_SIZE_BUFFER = 6120; 76 public static final int LARGE_SIZE_BUFFER = 10240; 77 78 private SynchronizedQueue small = new SynchronizedQueue(); 79 private SynchronizedQueue medium = new SynchronizedQueue(); 80 private SynchronizedQueue large = new SynchronizedQueue(); 81 82 83 84 87 public ByteBufferPool(int numOfSmall ,int numOfMedium, int numOfLarge) { 88 numInSmallPool = numOfSmall; 89 numInMediumPool = numOfMedium; 90 numInLargePool = numOfLarge; 91 92 for (int i = 0; i < ByteBufferPool.numInSmallPool; i++) { 93 small.enqueue(ByteBuffer.allocate(ByteBufferPool.SMALL_SIZE_BUFFER)); 94 } 96 for (int i = 0; i < ByteBufferPool.numInMediumPool; i++) { 97 medium.enqueue(ByteBuffer.allocate(ByteBufferPool.MEDIUM_SIZE_BUFFER)); 98 } 100 for (int i = 0; i < ByteBufferPool.numInLargePool; i++) { 101 large.enqueue(ByteBuffer.allocate(ByteBufferPool.LARGE_SIZE_BUFFER)); 102 } } 105 106 public final ByteBuffer getBuffer(int size){ 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 122 } 124 125 public final void release(ByteBuffer buffer){ 126 127 if(buffer==null) 129 return; 130 131 buffer.position(0); 132 buffer.limit(buffer.capacity()); 133 buffer.mark(); 134 int size = buffer.capacity(); 135 136 if(size == ByteBufferPool.SMALL_SIZE_BUFFER && small.size() < numInSmallPool) 137 small.enqueue(buffer); 138 else if(size == ByteBufferPool.MEDIUM_SIZE_BUFFER) 139 medium.enqueue(buffer); 140 else if(size == ByteBufferPool.LARGE_SIZE_BUFFER) 141 large.enqueue(buffer); 142 } 143 144 145 148 public int getSmallBufferSize() { 149 return SMALL_SIZE_BUFFER; 151 }} 153 154 | Popular Tags |