Skip to content

Commit

Permalink
Prefer VarHandle for ring buffer array
Browse files Browse the repository at this point in the history
  • Loading branch information
ben-manes committed Feb 8, 2021
1 parent f697f2b commit 6da53e7
Showing 1 changed file with 8 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.Consumer;

/**
Expand Down Expand Up @@ -56,12 +55,13 @@ protected Buffer<E> create(E e) {
}

static final class RingBuffer<E> extends BBHeader.ReadAndWriteCounterRef implements Buffer<E> {
final AtomicReferenceArray<E> buffer;
static final VarHandle BUFFER = MethodHandles.arrayElementVarHandle(Object[].class);

final Object[] buffer;

@SuppressWarnings({"unchecked", "cast", "rawtypes"})
public RingBuffer(E e) {
buffer = new AtomicReferenceArray<>(BUFFER_SIZE);
buffer.lazySet(0, e);
buffer = new Object[BUFFER_SIZE];
BUFFER.set(buffer, 0, e);
}

@Override
Expand All @@ -74,7 +74,7 @@ public int offer(E e) {
}
if (casWriteCounter(tail, tail + 1)) {
int index = (int) (tail & MASK);
buffer.lazySet(index, e);
BUFFER.setRelease(buffer, index, e);
return Buffer.SUCCESS;
}
return Buffer.FAILED;
Expand All @@ -90,12 +90,12 @@ public void drainTo(Consumer<E> consumer) {
}
do {
int index = (int) (head & MASK);
E e = buffer.get(index);
E e = (E) BUFFER.getVolatile(buffer, index);
if (e == null) {
// not published yet
break;
}
buffer.lazySet(index, null);
BUFFER.setRelease(buffer, index, null);
consumer.accept(e);
head++;
} while (head != tail);
Expand Down

0 comments on commit 6da53e7

Please sign in to comment.