Skip to content

Commit b6cd000

Browse files
authored
fix: prevent buffer stripe index overflow (#2331)
1 parent 7e7e533 commit b6cd000

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

  • prometheus-metrics-core/src

‎prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Buffer.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ class Buffer {
4343
}
4444

4545
boolean append(double value) {
46-
int index = Math.abs((int) Thread.currentThread().getId()) % stripedObservationCounts.length;
46+
int index = stripeIndex(Thread.currentThread().getId(), stripedObservationCounts.length);
4747
AtomicLong observationCountForThread = stripedObservationCounts[index];
4848
long count = observationCountForThread.incrementAndGet();
4949
if ((count & bufferActiveBit) == 0) {
@@ -54,6 +54,10 @@ boolean append(double value) {
5454
}
5555
}
5656

57+
static int stripeIndex(long threadId, int stripeCount) {
58+
return (int) Math.floorMod(threadId, stripeCount);
59+
}
60+
5761
private void doAppend(double amount) {
5862
appendLock.lock();
5963
try {
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package io.prometheus.metrics.core.metrics;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class BufferTest {
8+
9+
@Test
10+
void stripeIndexDoesNotOverflowWhenThreadIdNarrowsToIntegerMinValue() {
11+
assertThat(Buffer.stripeIndex(2_147_483_648L, 3)).isEqualTo(2);
12+
assertThat(Buffer.stripeIndex(2_147_483_648L, 6)).isEqualTo(2);
13+
assertThat(Buffer.stripeIndex(2_147_483_648L, 12)).isEqualTo(8);
14+
}
15+
}

0 commit comments

Comments
 (0)