forked from KNEMC/KLALB
优化代码,性能暴涨
This commit is contained in:
@@ -1,11 +1,19 @@
|
||||
package org.kne.cloud.network.klalb;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReferenceArray;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import org.kne.concurrent.SpinLock;
|
||||
import org.kne.debug.TimeDebugger;
|
||||
/*
|
||||
public class ByteBufferPool {
|
||||
private ArrayBlockingQueue<ByteBuffer>rec;
|
||||
private Queue<ByteBuffer> rec;
|
||||
private int maxcount;
|
||||
private int length;
|
||||
private boolean direct;
|
||||
@@ -14,7 +22,7 @@ public class ByteBufferPool {
|
||||
this.maxcount = maxcount;
|
||||
this.length = length;
|
||||
this.direct=direct;
|
||||
rec=new ArrayBlockingQueue<ByteBuffer>(length);
|
||||
rec=new ConcurrentLinkedQueue<ByteBuffer>();
|
||||
}
|
||||
public ByteBufferPool(int maxcount, int length) {
|
||||
this(maxcount, length, true);
|
||||
@@ -42,4 +50,64 @@ public class ByteBufferPool {
|
||||
return length;
|
||||
}
|
||||
|
||||
}*/
|
||||
|
||||
public class ByteBufferPool {
|
||||
private ByteBuffer[]rec;
|
||||
private volatile int pos=0;
|
||||
private Lock lock=new SpinLock();
|
||||
|
||||
private int maxcount;
|
||||
private int length;
|
||||
private int mcj;
|
||||
private boolean direct;
|
||||
public ByteBufferPool(int maxcount, int length,boolean direct) {
|
||||
super();
|
||||
this.maxcount = maxcount;
|
||||
this.length = length;
|
||||
this.direct=direct;
|
||||
rec=new ByteBuffer[maxcount];
|
||||
mcj=rec.length-1;
|
||||
}
|
||||
public ByteBufferPool(int maxcount, int length) {
|
||||
this(maxcount, length, true);
|
||||
}
|
||||
public void back(ByteBuffer b) {
|
||||
if(b.capacity()!=length)
|
||||
throw new IllegalArgumentException("wrong length");
|
||||
b.clear();
|
||||
lock.lock();
|
||||
try {
|
||||
if(pos<mcj)
|
||||
rec[++pos]= b;
|
||||
}finally{
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
public ByteBuffer borrow() {
|
||||
ByteBuffer b=null;
|
||||
lock.lock();
|
||||
try {
|
||||
if(pos>0) {
|
||||
b=rec[pos--];
|
||||
//rec[pos--]=null;
|
||||
}
|
||||
}finally{
|
||||
lock.unlock();
|
||||
}
|
||||
if(b==null) {
|
||||
if(direct)
|
||||
b=ByteBuffer.allocateDirect(length);
|
||||
else
|
||||
b=ByteBuffer.allocate(length);
|
||||
}
|
||||
return b;
|
||||
}
|
||||
public int getMaxCount() {
|
||||
return maxcount;
|
||||
}
|
||||
public int getLength() {
|
||||
return length;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user