I've been playing with CompletionStage/CompletableFuture in Java 8 in order to do asynchronous processing, which works quite well. However, sometimes I want a stage to perform asynchronous processing of an iterator/stream of items, and there doesn't seem to be a way to do this.
Specifically, Stream.forEach() has the semantics that after the call all items have been processed. I would want the same thing, but with a CompletionStage instead, e.g.:
CompletionStage<Void> done = stream.forEach(...); done.thenRun(...);
If the Stream is backed by an asynchronous streaming result this would be much better than waiting for it to be complete in the above code itself.
Is it possible to construct this with current Java 8 API somehow? Workarounds?
An Asynchronous call does not block the program from the code execution. When the call returns from the event, the call returns back to the callback function. So in the context of Java, we have to Create a new thread and invoke the callback method inside that thread.
Flows are quite different from Java 8 Streams: Streams are synchronous, hot, single-use, with very complex design geared for parallelization, while Flows are asynchronous, cold, multi-use, sequential and very simple in design.
Java concurrency is the functionality that enables asynchronous programming in Java. Concurrency is mainly the ability to run several programs or applications parallelly smoothly.
As far as I know, the streams API does not support asynchronous event processing. Sounds like you want something like Reactive Extensions for .NET, and there is a Java port of it called RxJava, created by Netflix.
RxJava supports many of the same high-level operations as Java 8 streams (such as map and filter) and is asynchronous.
Update: There is now a reactive streams initiative in the works, and it looks like JDK 9 will include support for at least part of it though the Flow class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With