From 9baf6950c01e4785a3f82752227599781dc2c7d3 Mon Sep 17 00:00:00 2001 From: Douglas Q Hawkins Date: Fri, 20 Nov 2026 23:50:45 -0500 Subject: [PATCH 1/2] Wake the event worker when an event arrives EventQueue's consumer parked in fixed 10 ms slices, because producers never signaled it. At more than capacity elements per 10 ms (410k a second for the flag-evaluation queue's 4,096 slots), the queue filled during each sleep and evaluations were dropped, however idle the worker was. A benchmark sweep showed drops jumping from about 1% to 8-72% right at that rate. A consumer that finds the queue empty now publishes itself as the waiter, checks again, and parks until its timeout; the producer that next queues an element and clears the waiter wakes it. Producers pay one volatile read per offer, and one unpark only when the consumer is parked. Co-Authored-By: Claude Opus 5.5 --- .../openfeature/internal/EventQueue.java | 33 ++++++++-- .../openfeature/internal/EventQueueTest.java | 60 +++++++++++++++++++ 2 files changed, 89 insertions(+), 4 deletions(-) diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/EventQueue.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/EventQueue.java index d2de2f8f239..c86262aaee4 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/EventQueue.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/EventQueue.java @@ -3,21 +3,31 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.locks.LockSupport; import java.util.function.Consumer; /** - * A bounded, lock-free, multiple-producer single-consumer queue. Producers never block; the - * consumer polls with a timeout by parking, as producers do not signal it. + * A bounded, lock-free, multiple-producer single-consumer queue. Producers never block. A consumer + * that finds the queue empty parks until the timeout, and the next producer to queue an element + * wakes it. + * + *

Without that wake-up, the consumer slept in fixed 10 ms slices: at more than {@code capacity} + * elements per 10 ms (410k a second for 4,096 slots), the queue filled during each sleep and + * producers dropped elements, however idle the consumer was. * * @param the element type. */ public final class EventQueue { - private static final long PARK_NANOS = TimeUnit.MILLISECONDS.toNanos(10); + @SuppressWarnings("rawtypes") + private static final AtomicReferenceFieldUpdater WAITER = + AtomicReferenceFieldUpdater.newUpdater(EventQueue.class, Thread.class, "waiter"); private final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); private final AtomicInteger size = new AtomicInteger(); private final int capacity; + // The consumer while it is about to park or parked, so a producer can wake it. + private volatile Thread waiter; public EventQueue(final int capacity) { this.capacity = capacity; @@ -38,6 +48,12 @@ public boolean offer(final E element) { return false; } this.queue.offer(element); + // One volatile read per offer. Only the producer that clears the waiter wakes it, so a burst + // of producers costs one unpark. + final Thread parked = this.waiter; + if (parked != null && WAITER.compareAndSet(this, parked, null)) { + LockSupport.unpark(parked); + } return true; } @@ -71,7 +87,16 @@ public E poll(final long timeout, final TimeUnit unit) throws InterruptedExcepti if (remaining <= 0) { return null; } - LockSupport.parkNanos(this, Math.min(remaining, PARK_NANOS)); + // Publish the waiter, then check again: a producer either sees the waiter and wakes it, or + // queued its element before this check, which then finds it. No wake-up is lost. + this.waiter = Thread.currentThread(); + final E queued = poll(); + if (queued != null) { + this.waiter = null; + return queued; + } + LockSupport.parkNanos(this, remaining); + this.waiter = null; if (Thread.interrupted()) { throw new InterruptedException(); } diff --git a/dd-openfeature/src/test/java/com/datadog/openfeature/internal/EventQueueTest.java b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/EventQueueTest.java index e2d62d88442..48a3d848a83 100644 --- a/dd-openfeature/src/test/java/com/datadog/openfeature/internal/EventQueueTest.java +++ b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/EventQueueTest.java @@ -12,6 +12,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; @@ -138,4 +139,63 @@ void concurrentProducersNeverExceedCapacity() throws Exception { assertEquals(capacity, accepted.get()); assertEquals(capacity, queue.size()); } + + @Test + void wakesAParkedConsumerWhenAnElementArrives() throws Exception { + final EventQueue queue = new EventQueue<>(16); + final ExecutorService consumer = Executors.newSingleThreadExecutor(); + try { + final long start = System.nanoTime(); + final Future polled = consumer.submit(() -> queue.poll(30, TimeUnit.SECONDS)); + MILLISECONDS.sleep(100); // let the consumer park + assertTrue(queue.offer("wake")); + // Without the wake-up, a consumer parked for the full timeout would sleep 30 s. + assertEquals("wake", polled.get(10, TimeUnit.SECONDS)); + assertTrue(System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); + } finally { + consumer.shutdownNow(); + } + } + + @Test + void losesNoWakeUpUnderContention() throws Exception { + final EventQueue queue = new EventQueue<>(64); + final int producers = 4; + final int perProducer = 20_000; + final AtomicInteger queued = new AtomicInteger(); + final ExecutorService executor = Executors.newFixedThreadPool(producers); + final CountDownLatch start = new CountDownLatch(1); + try { + for (int p = 0; p < producers; p++) { + executor.execute(() -> { + try { + start.await(); + } catch (InterruptedException e) { + return; + } + for (int i = 0; i < perProducer; i++) { + while (!queue.offer(i)) { + Thread.yield(); // full: retry, so every element is eventually queued + } + queued.incrementAndGet(); + } + }); + } + start.countDown(); + int consumed = 0; + final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + while (consumed < producers * perProducer) { + // Each element must arrive long before this timeout; a lost wake-up would stall here. + if (queue.poll(5, TimeUnit.SECONDS) != null) { + consumed++; + } + assertTrue(System.nanoTime() < deadline, "stalled after " + consumed); + } + assertEquals(producers * perProducer, consumed); + assertEquals(producers * perProducer, queued.get()); + assertNull(queue.poll()); + } finally { + executor.shutdownNow(); + } + } } From 1a0fb72f8b92449dc6a96ac037b52b4329aa23a3 Mon Sep 17 00:00:00 2001 From: Douglas Q Hawkins Date: Sat, 21 Nov 2026 00:51:02 -0500 Subject: [PATCH 2/2] Wake the event worker only once the queue is a quarter full MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Waking the consumer on every element stopped the drops, but at low rates the consumer keeps up and parks after each element, so nearly every offer paid an unpark: about 2 µs per evaluation on the producer. Park in slices of at most 10 ms again, and wake the consumer early only when an offer takes the queue to a quarter of its capacity. Below that, the slice bounds the delay at no cost to producers; above it, the consumer is woken with three quarters of the queue still free. Co-Authored-By: Claude Opus 5.5 --- .../openfeature/internal/EventQueue.java | 44 +++++++++++++------ .../openfeature/internal/EventQueueTest.java | 30 ++++++++++--- 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/EventQueue.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/EventQueue.java index c86262aaee4..40272977da3 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/EventQueue.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/EventQueue.java @@ -9,12 +9,14 @@ /** * A bounded, lock-free, multiple-producer single-consumer queue. Producers never block. A consumer - * that finds the queue empty parks until the timeout, and the next producer to queue an element - * wakes it. + * that finds the queue empty parks in slices of at most 10 ms, and a producer wakes it early only + * once the queue is a quarter full. * - *

Without that wake-up, the consumer slept in fixed 10 ms slices: at more than {@code capacity} - * elements per 10 ms (410k a second for 4,096 slots), the queue filled during each sleep and - * producers dropped elements, however idle the consumer was. + *

Without the early wake-up, at more than {@code capacity} elements per 10 ms (410k a second for + * 4,096 slots) the queue filled during each sleep and producers dropped elements, however idle the + * consumer was. Waking on every element fixes that but is worse at low rates: the consumer keeps + * up, parks after every element, and nearly every offer pays an unpark, a system call and a context + * switch costing microseconds. Below the threshold, the slice bounds the delay instead. * * @param the element type. */ @@ -25,12 +27,23 @@ public final class EventQueue { private final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); private final AtomicInteger size = new AtomicInteger(); + private static final long MAX_PARK_NANOS = TimeUnit.MILLISECONDS.toNanos(10); + private final int capacity; + // The queue size at which a producer wakes a parked consumer. + private final int wakeThreshold; + private final long maxParkNanos; // The consumer while it is about to park or parked, so a producer can wake it. private volatile Thread waiter; public EventQueue(final int capacity) { + this(capacity, Math.max(1, capacity >> 2), MAX_PARK_NANOS); + } + + EventQueue(final int capacity, final int wakeThreshold, final long maxParkNanos) { this.capacity = capacity; + this.wakeThreshold = wakeThreshold; + this.maxParkNanos = maxParkNanos; } /** @@ -43,16 +56,19 @@ public boolean offer(final E element) { if (element == null) { throw new NullPointerException("element"); } - if (this.size.incrementAndGet() > this.capacity) { + final int queued = this.size.incrementAndGet(); + if (queued > this.capacity) { this.size.decrementAndGet(); return false; } this.queue.offer(element); - // One volatile read per offer. Only the producer that clears the waiter wakes it, so a burst - // of producers costs one unpark. - final Thread parked = this.waiter; - if (parked != null && WAITER.compareAndSet(this, parked, null)) { - LockSupport.unpark(parked); + // Below the threshold the consumer's next slice finds the element, at no cost here. Above it, + // only the producer that clears the waiter wakes it, so a burst costs one unpark. + if (queued >= this.wakeThreshold) { + final Thread parked = this.waiter; + if (parked != null && WAITER.compareAndSet(this, parked, null)) { + LockSupport.unpark(parked); + } } return true; } @@ -87,15 +103,15 @@ public E poll(final long timeout, final TimeUnit unit) throws InterruptedExcepti if (remaining <= 0) { return null; } - // Publish the waiter, then check again: a producer either sees the waiter and wakes it, or - // queued its element before this check, which then finds it. No wake-up is lost. + // Publish the waiter, then check again: a producer crossing the threshold either sees the + // waiter and wakes it, or queued its element before this check, which then finds it. this.waiter = Thread.currentThread(); final E queued = poll(); if (queued != null) { this.waiter = null; return queued; } - LockSupport.parkNanos(this, remaining); + LockSupport.parkNanos(this, Math.min(remaining, this.maxParkNanos)); this.waiter = null; if (Thread.interrupted()) { throw new InterruptedException(); diff --git a/dd-openfeature/src/test/java/com/datadog/openfeature/internal/EventQueueTest.java b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/EventQueueTest.java index 48a3d848a83..6d75805b3e8 100644 --- a/dd-openfeature/src/test/java/com/datadog/openfeature/internal/EventQueueTest.java +++ b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/EventQueueTest.java @@ -14,6 +14,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; @@ -141,17 +142,34 @@ void concurrentProducersNeverExceedCapacity() throws Exception { } @Test - void wakesAParkedConsumerWhenAnElementArrives() throws Exception { + void findsAnElementBelowTheThresholdWithinOneSlice() throws Exception { final EventQueue queue = new EventQueue<>(16); final ExecutorService consumer = Executors.newSingleThreadExecutor(); try { - final long start = System.nanoTime(); final Future polled = consumer.submit(() -> queue.poll(30, TimeUnit.SECONDS)); MILLISECONDS.sleep(100); // let the consumer park - assertTrue(queue.offer("wake")); - // Without the wake-up, a consumer parked for the full timeout would sleep 30 s. - assertEquals("wake", polled.get(10, TimeUnit.SECONDS)); - assertTrue(System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); + assertTrue(queue.offer("one")); + // No wake-up below the threshold: the consumer's next 10 ms slice finds it. + assertEquals("one", polled.get(10, TimeUnit.SECONDS)); + } finally { + consumer.shutdownNow(); + } + } + + @Test + void wakesAParkedConsumerOnlyOnceTheQueueReachesTheThreshold() throws Exception { + // Slices as long as the timeout, so only a wake-up ends the park early. + final EventQueue queue = new EventQueue<>(16, 3, TimeUnit.SECONDS.toNanos(30)); + final ExecutorService consumer = Executors.newSingleThreadExecutor(); + try { + final Future polled = consumer.submit(() -> queue.poll(30, TimeUnit.SECONDS)); + MILLISECONDS.sleep(100); // let the consumer park + assertTrue(queue.offer("a")); + assertTrue(queue.offer("b")); + assertThrows(TimeoutException.class, () -> polled.get(200, MILLISECONDS)); + + assertTrue(queue.offer("c")); + assertEquals("a", polled.get(10, TimeUnit.SECONDS)); } finally { consumer.shutdownNow(); }