SubmissionPublisher
- Java course
- Expert
- Lesson 21/46
- 5 min
Learn data publishing with SubmissionPublisher.
SubmissionPublisher
SubmissionPublisher is the JDK's ready-made Publisher implementation. It makes it easy to create an asynchronous flow without writing your own Publisher class. Items are sent with submit, and the flow is closed with close.
Example: SubmissionPublisher<String> pub = new SubmissionPublisher<>(). A subscriber is added with pub.subscribe(sub), and an item is sent with pub.submit("data"). SubmissionPublisher distributes items asynchronously on a thread pool. So a short wait after close may be needed for the flow to finish.
Watching the subscriber count
How many subscribers a SubmissionPublisher has is learned with getNumberOfSubscribers. This is useful in systems that manage several subscribers. getSubscribers also gives the subscriber list.
Example: after pub.subscribe(a); pub.subscribe(b);, pub.getNumberOfSubscribers() returns two. This value drops after an unsubscribe. So the current subscriber count of the publisher can be watched synchronously.
Practice Print the subscriber count
Define an EmptySubscriber class that implements Subscriber<String> (methods can be empty; onSubscribe calls request(1)). In main, create new SubmissionPublisher<String>(), subscribe one EmptySubscriber, and print the getNumberOfSubscribers result with System.out.println. Then close with pub.close().
Starter code
// Create a SubmissionPublisher
// Add one subscriber
// Print the subscriber countSample solution
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.Flow.*;
class EmptySubscriber implements Subscriber<String> {
public void onSubscribe(Subscription s) { s.request(1); }
public void onNext(String v) { }
public void onError(Throwable t) { }
public void onComplete() { }
}
public class SubmissionDemo {
public static void main(String[] args) {
SubmissionPublisher<String> pub = new SubmissionPublisher<>();
pub.subscribe(new EmptySubscriber());
System.out.println(pub.getNumberOfSubscribers());
pub.close();
}
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Create a SubmissionPublisher
SubmissionPublisher<String> pub = ____<>();
SubmissionPublisher<String> pub = new SubmissionPublisher<>();
Explanation: new SubmissionPublisher is a ready publisher.
2 Match the SubmissionPublisher methods
| Term | Meaning |
|---|---|
SubmissionPublisher |
Ready Publisher |
submit |
Sends an item |
subscribe |
Adds a subscriber |
close |
Closes the flow |
3 What does SubmissionPublisher make easier?
- File reading
- Creating a Publisher Correct answer
- String encoding
- Path operations
Explanation: SubmissionPublisher is a ready Publisher implementation.