Busy-spin in `OutputStreamPublisher.await()` when interrupted while awaiting demand
Affects: main, 7.0.x and 6.2.x (same code on all three branches)
gh-37159 fixed a busy-spin in SubscriberInputStream.await(). OutputStreamPublisher has the same await() loop, in both copies, and it still spins:
spring-core:org.springframework.core.io.buffer.OutputStreamPublisher, used byDataBufferUtils.outputStreamPublisherandBodyInserters.fromOutputStreamspring-web:org.springframework.http.client.OutputStreamPublisher, used byJdkClientHttpRequestandReactorClientHttpRequestto write request bodies
if (this.parkedThread.compareAndSet(null, toUnpark)) {
LockSupport.park();
}
The writer thread parks here when the subscriber has no outstanding demand, for example when uploading to a slow server. If park() returns without resume(), parkedThread still holds the writer thread. That happens on an interrupt or a spurious wakeup. From then on the CAS always fails, so the loop neither parks nor exits. The interrupt flag is never cleared either, so it spins at 100% CPU until the subscriber requests more or cancels.
One way to interrupt the writer is to shut down the executor that runs the writes with shutdownNow(). ThreadPoolTaskExecutor does this on shutdown unless waitForTasksToCompleteOnShutdown is set. Future.cancel(true) does it too, as does body code that catches InterruptedException, restores the flag and keeps writing. On virtual threads, a spinning writer never gives back its carrier, which is the same concern as in gh-37159.
To be clear: I found this by comparing the code with the gh-37159 fix, not from a production incident.
Reproducer
This test uses only public API (DataBufferUtils.outputStreamPublisher). It fails on main:
@Test
void interruptWhileAwaitingDemand() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
AtomicReference<Thread> writer = new AtomicReference<>();
CountDownLatch writerDone = new CountDownLatch(1);
Flux<DataBuffer> body = Flux.from(DataBufferUtils.outputStreamPublisher(out -> {
writer.set(Thread.currentThread());
try {
out.write("foo".getBytes());
out.flush(); // demand 1: emitted
out.write("bar".getBytes());
out.flush(); // no demand: writer parks here
}
catch (IOException ex) {
// fine, as long as we get out
}
finally {
writerDone.countDown();
}
}, DefaultDataBufferFactory.sharedInstance, executor));
BaseSubscriber<DataBuffer> slowConsumer = new BaseSubscriber<>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
request(1); // then no more demand, like a slow peer
}
};
body.subscribe(slowConsumer);
while (writer.get() == null || writer.get().getState() != Thread.State.WAITING) {
Thread.sleep(10);
}
long cpuBefore = cpuTime(writer.get());
executor.shutdownNow(); // interrupts the writer
Thread.sleep(500);
long cpuMillis = (cpuTime(writer.get()) - cpuBefore) / 1_000_000;
Thread.State state = writer.get().getState();
slowConsumer.cancel();
writerDone.await(5, TimeUnit.SECONDS);
System.out.println("writer state after interrupt: " + state + ", CPU used in 500ms: " + cpuMillis + "ms");
assertThat(state).isNotEqualTo(Thread.State.RUNNABLE);
}
@SuppressWarnings("deprecation")
private static long cpuTime(Thread thread) {
return ManagementFactory.getThreadMXBean().getThreadCpuTime(thread.getId());
}
| writer thread 500 ms after interrupt | CPU used in those 500 ms | |
|---|---|---|
main |
RUNNABLE |
501 ms |
| with the fix below | TERMINATED |
0 ms |
Possible fix
The same change as gh-37159, applied to both copies:
- Park again while the reference is still ours.
- On interrupt, restore the flag, clear the reference and throw an
InterruptedIOException.
checkDemandAndAwaitIfNeeded() already declares IOException, and invokeHandler turns that into onError. I tried this locally on both copies: the reproducer passes, and so do DataBufferUtilsTests, OutputStreamPublisherTests and the JDK/Reactor ClientHttpRequestFactory tests.
I'd be happy to submit a PR with the fix and tests once this is triaged. I assume it should go into 7.0.x, as gh-37159 did. Is that right?
I'd like to take this.
Same fix shape as #37159 / SubscriberInputStream.await(): park while the reference is still ours, and on interrupt restore the flag, clear the reference, and throw InterruptedIOException. I'll cover both spring-core and spring-web copies plus a regression test.