FileDocCategorySizeDatePackage
BufferPool.javaAPI DocAndroid 5.1 API2947Thu Mar 12 22:22:42 GMT 2015com.android.accessorydisplay.common

BufferPool

public final class BufferPool extends Object
Maintains a bounded pool of buffers. Attempts to acquire buffers beyond the maximum count will block until other buffers are released.

Fields Summary
private final int
mInitialBufferSize
private final int
mMaxBufferSize
private final ByteBuffer[]
mBuffers
private int
mAllocated
private int
mAvailable
Constructors Summary
public BufferPool(int initialBufferSize, int maxBufferSize, int maxBuffers)

        mInitialBufferSize = initialBufferSize;
        mMaxBufferSize = maxBufferSize;
        mBuffers = new ByteBuffer[maxBuffers];
    
Methods Summary
public java.nio.ByteBufferacquire(int needed)

        synchronized (this) {
            for (;;) {
                if (mAvailable != 0) {
                    mAvailable -= 1;
                    return grow(mBuffers[mAvailable], needed);
                }

                if (mAllocated < mBuffers.length) {
                    mAllocated += 1;
                    return ByteBuffer.allocate(chooseCapacity(mInitialBufferSize, needed));
                }

                try {
                    wait();
                } catch (InterruptedException ex) {
                }
            }
        }
    
private intchooseCapacity(int capacity, int needed)

        while (capacity < needed) {
            capacity *= 2;
        }
        if (capacity > mMaxBufferSize) {
            if (needed > mMaxBufferSize) {
                throw new IllegalArgumentException("Requested size " + needed
                        + " is larger than maximum buffer size " + mMaxBufferSize + ".");
            }
            capacity = mMaxBufferSize;
        }
        return capacity;
    
public java.nio.ByteBuffergrow(java.nio.ByteBuffer buffer, int needed)

        int capacity = buffer.capacity();
        if (capacity < needed) {
            final ByteBuffer oldBuffer = buffer;
            capacity = chooseCapacity(capacity, needed);
            buffer = ByteBuffer.allocate(capacity);
            oldBuffer.flip();
            buffer.put(oldBuffer);
        }
        return buffer;
    
public voidrelease(java.nio.ByteBuffer buffer)

        synchronized (this) {
            buffer.clear();
            mBuffers[mAvailable++] = buffer;
            notifyAll();
        }