public ByteBuffer allocate(int capacity, boolean direct) { ensureNotDisposed(); UnexpandableByteBuffer ubb = allocate0(capacity, direct); PooledByteBuffer buf = allocateContainer(); buf.init(ubb, true); return buf; }
public ByteBuffer wrap(java.nio.ByteBuffer nioBuffer) { ensureNotDisposed(); PooledByteBuffer buf = allocateContainer(); buf.init(new UnexpandableByteBuffer(nioBuffer), false); buf.buf.init(); buf.setPooled(false); return buf; }
private void release0(UnexpandableByteBuffer buf) { ExpiringStack[] bufferStacks = buf.buf().isDirect() ? directBufferStacks : heapBufferStacks; ExpiringStack stack = bufferStacks[getBufferStackIndex(bufferStacks, buf.buf().capacity())]; synchronized (stack) { // push back stack.push(buf); } }
/** * Creates a new instance with the specified <tt>timeout</tt>. */ public PooledByteBufferAllocator(int timeout) { setTimeout(timeout); expirer = new Expirer(); expirer.start(); }
public void run() { // Expire unused buffers every seconds while (!timeToStop) { try { Thread.sleep(1000); } catch (InterruptedException e) { //ignore } // Check if expiration is disabled. long timeout = getTimeoutMillis(); if (timeout <= 0L) { continue; } // Expire old buffers long expirationTime = System.currentTimeMillis() - timeout; for (int i = directBufferStacks.length - 1; i >= 0; i--) { ExpiringStack stack = directBufferStacks[i]; synchronized (stack) { stack.expireBefore(expirationTime); } } for (int i = heapBufferStacks.length - 1; i >= 0; i--) { ExpiringStack stack = heapBufferStacks[i]; synchronized (stack) { stack.expireBefore(expirationTime); } } } } }
private static ByteBufferAllocator allocator = new PooledByteBufferAllocator();
private UnexpandableByteBuffer allocate0(int capacity, boolean direct) { ExpiringStack[] bufferStacks = direct ? directBufferStacks : heapBufferStacks; int idx = getBufferStackIndex(bufferStacks, capacity); ExpiringStack stack = bufferStacks[idx]; UnexpandableByteBuffer buf; synchronized (stack) { buf = (UnexpandableByteBuffer) stack.pop(); } if (buf == null) { java.nio.ByteBuffer nioBuf = direct ? java.nio.ByteBuffer .allocateDirect(MINIMUM_CAPACITY << idx) : java.nio.ByteBuffer.allocate(MINIMUM_CAPACITY << idx); buf = new UnexpandableByteBuffer(nioBuf); } buf.init(); return buf; }