Skip to content

Commit 8cd599d

Browse files
committed
Simplify and make more fair the spin wait
1 parent 74e343c commit 8cd599d

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

internal-api/internal-api-9/src/main/java/datadog/trace/util/queue/MpscArrayQueueVarHandle.java

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import java.lang.invoke.MethodHandles.Lookup;
55
import java.lang.invoke.VarHandle;
66
import java.util.Objects;
7-
import java.util.concurrent.ThreadLocalRandom;
87
import java.util.concurrent.locks.LockSupport;
98

109
/**
@@ -89,6 +88,9 @@ public boolean offer(E e) {
8988
long localProducerLimit = (long) PRODUCER_LIMIT_HANDLE.getVolatile(this);
9089
long cachedHead = 0L; // Local cache of head to reduce volatile reads
9190

91+
int spinCycles = 0;
92+
boolean parkOnSpin = (Thread.currentThread().getId() & 1) == 0;
93+
9294
while (true) {
9395
long currentTail = (long) TAIL_HANDLE.getVolatile(this);
9496

@@ -116,20 +118,16 @@ public boolean offer(E e) {
116118
}
117119

118120
// Backoff to reduce contention
119-
switch (ThreadLocalRandom.current().nextInt(0, 4)) {
120-
case 0:
121-
Thread.yield();
122-
break;
123-
case 1:
121+
if ((spinCycles & 1) == 0) {
122+
Thread.onSpinWait();
123+
} else {
124+
if (parkOnSpin) {
124125
LockSupport.parkNanos(1);
125-
break;
126-
case 2:
127-
Thread.onSpinWait();
128-
break;
129-
default:
130-
// busy spin
131-
break;
126+
} else {
127+
Thread.yield();
128+
}
132129
}
130+
spinCycles++;
133131
}
134132
}
135133

0 commit comments

Comments
 (0)