SubmissionPublisher Flow With Backpressure
Push readings through SubmissionPublisher, whose subscriber pulls items and exposes a future that completes only after everything is consumed.
Code
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.SubmissionPublisher;
public class SensorFeed {
public static void main(String[] args) {
try (SubmissionPublisher<Integer> publisher = new SubmissionPublisher<>()) {
// consume() 返回的 future 在发布者 onComplete 后才完成:
// 订阅端按需拉取,节奏由消费方决定而不是生产方
CompletableFuture<Void> drained = publisher.consume(reading ->
System.out.println("received: " + reading));
publisher.submit(21);
publisher.submit(22);
publisher.submit(23);
publisher.close();
drained.join(); // 不等消费完成就退出会丢掉尾部数据
System.out.println("all readings consumed");
}
}
}Inside the snippet
Count the class SensorFeed and the function main as the entire surface area of SubmissionPublisher Flow With Backpressure.
Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Putting it to use
Running the file prints labeled results such as received:, all readings consumed — each operation’s effect is visible in the output.
Core lines
CompletableFuture<Void> drained = publisher.consume(reading ->
System.out.println("received: " + reading));
Interactive Tools for This Topic
FAQ
- What does SubmissionPublisher Flow With Backpressure print when run?
- Invoke the file as-is — the `received:`, `all readings consumed` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.