forked from KNEMC/KLALB
114 lines
2.5 KiB
Java
114 lines
2.5 KiB
Java
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 Queue<ByteBuffer> rec;
|
|
private int maxcount;
|
|
private int length;
|
|
private boolean direct;
|
|
public ByteBufferPool(int maxcount, int length,boolean direct) {
|
|
super();
|
|
this.maxcount = maxcount;
|
|
this.length = length;
|
|
this.direct=direct;
|
|
rec=new ConcurrentLinkedQueue<ByteBuffer>();
|
|
}
|
|
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();
|
|
rec.offer(b);
|
|
}
|
|
public ByteBuffer borrow() {
|
|
ByteBuffer b=rec.poll();
|
|
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;
|
|
}
|
|
|
|
}*/
|
|
|
|
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;
|
|
}
|
|
|
|
}
|