write and read sequence volatile
This commit is contained in:
parent
5263fbf070
commit
a4efb737a8
|
@ -2,27 +2,35 @@ package com.baeldung.circularbuffer;
|
||||||
|
|
||||||
public class CircularBuffer<E> {
|
public class CircularBuffer<E> {
|
||||||
|
|
||||||
private int capacity, writeIndex, readIndex;
|
private static final int DEFAULT_CAPACITY = 8;
|
||||||
private E[] data;
|
|
||||||
|
private final int capacity;
|
||||||
|
private final E[] data;
|
||||||
|
private volatile int writeSequence, readSequence;
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public CircularBuffer(int capacity) {
|
public CircularBuffer(int capacity) {
|
||||||
|
|
||||||
this.capacity = capacity;
|
this.capacity = (capacity < 1 ? DEFAULT_CAPACITY : capacity);
|
||||||
this.data = (E[]) new Object[capacity];
|
this.data = (E[]) new Object[capacity];
|
||||||
|
|
||||||
this.readIndex = 0;
|
this.readSequence = 0;
|
||||||
this.writeIndex = -1;
|
this.writeSequence = -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a new element to the buffer, if the buffer is not full
|
||||||
|
* @param element
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
public boolean offer(E element) {
|
public boolean offer(E element) {
|
||||||
|
|
||||||
if (!isFull()) {
|
if (!isFull()) {
|
||||||
|
|
||||||
writeIndex += 1;
|
int nextWriteSeq = writeSequence + 1;
|
||||||
int nextWriteIndex = writeIndex % capacity;
|
data[nextWriteSeq % capacity] = element;
|
||||||
data[nextWriteIndex] = element;
|
|
||||||
|
|
||||||
|
writeSequence += 1;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -33,20 +41,9 @@ public class CircularBuffer<E> {
|
||||||
|
|
||||||
if (!isEmpty()) {
|
if (!isEmpty()) {
|
||||||
|
|
||||||
int nextReadIndex = readIndex % capacity;
|
E nextValue = data[readSequence % capacity];
|
||||||
readIndex += 1;
|
readSequence += 1;
|
||||||
|
return nextValue;
|
||||||
return data[nextReadIndex];
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public E peek() {
|
|
||||||
|
|
||||||
if (!isEmpty()) {
|
|
||||||
|
|
||||||
return data[readIndex % capacity];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
@ -58,12 +55,12 @@ public class CircularBuffer<E> {
|
||||||
|
|
||||||
public int size() {
|
public int size() {
|
||||||
|
|
||||||
return (writeIndex - readIndex) + 1;
|
return (writeSequence - readSequence) + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isEmpty() {
|
public boolean isEmpty() {
|
||||||
|
|
||||||
return writeIndex < readIndex;
|
return writeSequence < readSequence;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isFull() {
|
public boolean isFull() {
|
||||||
|
|
Loading…
Reference in New Issue