Skip to content

Instantly share code, notes, and snippets.

@ashkrit
Last active June 23, 2020 15:07
Show Gist options
  • Select an option

  • Save ashkrit/044aa096c7f5537072dd03581bf2e8e9 to your computer and use it in GitHub Desktop.

Select an option

Save ashkrit/044aa096c7f5537072dd03581bf2e8e9 to your computer and use it in GitHub Desktop.
public class RingBuffer<T> {
public RingBuffer(int size) {
this.capacity = Bits.powOf2(size);
this.mask = capacity - 1;
buffer = new Object[this.capacity];
}
private int offset(int index) {return index & mask;
//return index % capacity;
}
public boolean write(T value) {
if (buffer[offset(write)] != null)
return false;
buffer[offset(write++)] = value;
return true;
}
public T read() {
if (read == write)
return null;
T value = (T) buffer[offset(read)];
buffer[offset(read++)] = null;
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment