Circular Buffer

From Coder's Log

Jump to: navigation, search


The sample bellow is how you can create a circular buffer of smaller buffer objects, same could be applied to an array . Also this version allows for buffer to be returned but at the same time it doesn't get incremented until one of the success methods is called.

public class CircularBuffer {
	private ByteBuffer[] buffers;
	private int limit;
	private int position;

	public CircularBuffer(int bufferCount, int bufferSize) {
		buffers = new ByteBuffer[bufferCount];
		for (int i = 0; i < buffers.length; i++)
			buffers[i] = ByteBuffer.allocate(bufferSize);
	}
	public ByteBuffer getBufferForReading() {
		if (isEmpty())
			return null;
		return buffers[position % buffers.length];
	}
	public ByteBuffer getBufferForWriting() {
		if (isFull())
			return null;
		return buffers[limit % buffers.length];
	}
	public void bufferWriteSuccess() {
		limit++;
	}
	public void bufferReadSuccess()	{
		position++;
	}
	public boolean isFull() {
		return limit - position >= buffers.length;
	}
	public boolean isEmpty() {
		return limit == position;
	}
}
Personal tools