Andres Riofrio
Andres Riofrio

Reputation: 10357

How to use an infinite java.util.stream.Stream?

Say I have an infinite Stream:

Stream<Socket> stream = Stream.generate(() -> {
    try {
        return serverSocket.accept();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
});

I want to be able to use it kind of like this:

stream.forEach(socket -> {
    new Thread(() -> {
        socket.getOutputStream().write("Hi there, client.");
    });
});

But this doesn't seem to work, and it's probably because I'm misunderstanding a critical aspect of Java 8 Streams. What am I doing wrong?

Upvotes: 2

Views: 543

Answers (2)

srborlongan
srborlongan

Reputation: 4579

A variant of @Andres Riofrio's answer:

stream
  .<Runnable>map(socket -> () ->
    socket
      .getOutputStream()
      .write("Hi there, client.")
  ) // create a Runnable that writes a string to the socket's output stream
  .map(Thread::new) // transform each Runnable into a Thread
  .forEach(Thread::start) // start each Thread
;

Upvotes: 7

Andres Riofrio
Andres Riofrio

Reputation: 10357

Actually, my problem was that I forgot to start the thread:

stream.forEach(socket -> {
    new Thread(() -> {
        socket.getOutputStream().write("Hi there, client.");
    }).start();
});

Upvotes: 3

Related Questions