Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Java 8 Streams API for asynchronous processing?

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?

like image 609
Rickard Öberg Avatar asked Jul 31 '13 02:07

Rickard Öberg


People also ask

What is asynchronous API in Java?

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.

Are Java streams synchronous?

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.

Does Java support asynchronous programming?

Java concurrency is the functionality that enables asynchronous programming in Java. Concurrency is mainly the ability to run several programs or applications parallelly smoothly.


1 Answers

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.

like image 151
Soulman Avatar answered Sep 17 '22 04:09

Soulman