1 46 51 package org.mr.core.util.byteable; 52 53 import java.nio.ByteBuffer ; 54 55 import org.mr.core.util.SynchronizedQueue; 56 57 62 public class UnboundedByteBufferPool implements ByteBufferFactory{ 63 64 65 66 private SynchronizedQueue small = new SynchronizedQueue(); 67 private SynchronizedQueue medium = new SynchronizedQueue(); 68 private SynchronizedQueue large = new SynchronizedQueue(); 69 70 private ByteBufferPoolParameters params; 71 72 75 public UnboundedByteBufferPool(ByteBufferPoolParameters params) { 76 this.params = params; 77 78 for (int i = 0; i < params.getNumInSmallPool(); i++) { 79 small.enqueue(ByteBuffer.allocate( params.getSmallBufferSize())); 80 } 82 for (int i = 0; i < params.getNumInMediumPool(); i++) { 83 medium.enqueue(ByteBuffer.allocate( params.getMediumBufferSize())); 84 } 86 for (int i = 0; i < params.getNumInLargePool(); i++) { 87 large.enqueue(ByteBuffer.allocate( params.getLargeBufferSize())); 88 } } 91 static int count = 0; 92 public final ByteBuffer getBuffer(int size){ 93 if(size > 2000){ 94 int y =1; 95 } 97 98 ByteBuffer result = null; 99 if(size <= params.getSmallBufferSize()){ 100 result= (ByteBuffer )small.dequeueNoBlock(); }else if(size <= params.getMediumBufferSize()){ 102 result= (ByteBuffer )medium.dequeueNoBlock(); 104 }else if(size <= params.getLargeBufferSize()){ 105 result= (ByteBuffer )large.dequeueNoBlock(); } 107 if(result == null){ 108 result= ByteBuffer.allocate(size); 110 } 111 112 result.limit(size); 113 return result; 114 115 } 117 118 public final void release(ByteBuffer buffer){ 119 120 if(buffer==null) 122 return; 123 124 buffer.position(0); 125 buffer.limit(buffer.capacity()); 126 buffer.mark(); 127 int size = buffer.capacity(); 128 129 if(size == params.getSmallBufferSize() && small.size() < params.getNumInSmallPool()) 130 small.enqueue(buffer); 131 else if(size == params.getMediumBufferSize() && medium.size() < params.getNumInMediumPool()){ 132 medium.enqueue(buffer); 133 134 }else if(size == params.getLargeBufferSize() && large.size() < params.getNumInLargePool()) 135 large.enqueue(buffer); 136 } 138 139 142 public int getSmallBufferSize() { 143 144 return params.getSmallBufferSize(); 145 } 146 } 147 148 | Popular Tags |