Skip to content

Commit 02dfec2

Browse files
committed
Revert "Use getAndAdd for the offer fast path"
This reverts commit 14cc597.
1 parent 327a951 commit 02dfec2

File tree

1 file changed

+7
-17
lines changed

1 file changed

+7
-17
lines changed

utils/queue-utils/src/main/java/datadog/common/queue/MpscArrayQueueVarHandle.java

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,9 @@ public MpscArrayQueueVarHandle(int requestedCapacity) {
8282
public boolean offer(E e) {
8383
Objects.requireNonNull(e);
8484

85+
// jctools does the same local copy to have the jitter optimise the accesses
8586
final Object[] localBuffer = this.buffer;
87+
8688
long localProducerLimit = (long) PRODUCER_LIMIT_HANDLE.getVolatile(this);
8789
long cachedHead = 0L; // Local cache of head to reduce volatile reads
8890

@@ -92,45 +94,33 @@ public boolean offer(E e) {
9294
while (true) {
9395
long currentTail = (long) TAIL_HANDLE.getVolatile(this);
9496

95-
// Slow path: refresh producer limit when queue is near full
97+
// Check if producer limit exceeded
9698
if (currentTail >= localProducerLimit) {
99+
// Refresh head only when necessary
97100
cachedHead = (long) HEAD_HANDLE.getVolatile(this);
98101
localProducerLimit = cachedHead + capacity;
99102

100103
if (currentTail >= localProducerLimit) {
101104
return false; // queue full
102105
}
103106

107+
// Update producerLimit so other producers also benefit
104108
PRODUCER_LIMIT_HANDLE.setVolatile(this, localProducerLimit);
105109
}
106110

107-
long freeSlots = localProducerLimit - currentTail;
108-
109-
// Fast path: getAndAdd if occupancy < 75%
110-
if (freeSlots > (long) (capacity * 0.25)) { // more than 25% free
111-
long slot = (long) TAIL_HANDLE.getAndAdd(this, 1L);
112-
final int index = (int) (slot & mask);
113-
114-
// Release-store ensures visibility to consumer
115-
ARRAY_HANDLE.setRelease(localBuffer, index, e);
116-
return true;
117-
}
118-
119-
// Slow path: CAS near limit
111+
// Attempt to claim a slot
120112
if (TAIL_HANDLE.compareAndSet(this, currentTail, currentTail + 1)) {
121113
final int index = (int) (currentTail & mask);
122114

123-
// Release-store ensures visibility to consumer
115+
// Release-store ensures producer's write is visible to consumer
124116
ARRAY_HANDLE.setRelease(localBuffer, index, e);
125117
return true;
126118
}
127119

128120
// Backoff to reduce contention
129121
if ((spinCycles & 1) == 0) {
130-
// spin each even cycles
131122
Thread.onSpinWait();
132123
} else {
133-
// use a 'random' alternate backoff on odd cycles
134124
if (parkOnSpin) {
135125
LockSupport.parkNanos(1);
136126
} else {

0 commit comments

Comments
 (0)