I've written a circular buffer with multithreaded write and single read ability:
public class RingBuffer<E> extends AbstractList<E> implements RandomAccess {
class Pointer {
int p = 0;
public int getPointer(){
return this.p;
}
public void increasePointer(int p) {
this.p = p;
}
}
private final int n;
private final List<E> rb;
private int size = 0;
private Pointer ptr_w = new Pointer();
private Pointer ptr_r = new Pointer();
public RingBuffer(int n) {
this.n = n + 1;
this.rb = new ArrayList<E>(Collections.nCopies(this.n, (E) null));
}
public int size() {
return this.size;
}
private int wrap(int i) {
int m = i % this.n;
return (m < 0) ? m += this.n : m;
}
@Override
public E get(int i) {
return (this.size == 0) ? null : this.rb.get(i);
}
@Override
public E remove(int i) {
E e = this.get(this.ptr_r.getPointer());
if(e != null) {
this.rb.set(this.ptr_r.getPointer(), null);
setPointer(false, this.ptr_r);
}
System.out.println("Read: " + this.ptr_r.getPointer() + " " + size());
return e;
}
@Override
public synchronized boolean add(E e) {
if (size() == this.n - 1)
throw new IllegalStateException("Cannot add element. Ringbuffer is filled.");
this.rb.set(this.ptr_w.getPointer(), e);
setPointer(true, this.ptr_w);
System.out.println("Write: " + this.ptr_w.getPointer() + " " + size());
return true;
}
private synchronized void setPointer(boolean a, Pointer ptr) {
this.size = (a) ? this.size + 1 : this.size - 1;
ptr.increasePointer(wrap(ptr.getPointer() + 1));
}
}
I would like to know what I could improve and what you think about the code. I'm new to multithreading and would love to get some feedback.