Bret Fontecchio
Bret Fontecchio

Reputation: 649

When Does Scanner.nextLine() block?

I'm using a Scanner for my socket connection in a Client/Server program.

I want Scanner.next() to block so the Server thread can wait for something to read.

However, it sometimes gives me:

java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1585)
    at cscie55.hw4.Server.serviceClient(Server.java:146)
    at cscie55.hw4.Server.main(Server.java:106)

The java documentation says that next() "sometimes" blocks, and it doesn't say whether nextLine() blocks.

Some code online wraps it in an if that tests for null, but I read that it never returns null. What should I do to get blocking IO working properly in my socket?

Specifically,

When does Scanner.nextLine() block rather than throw NoSuchElementException?

Upvotes: 1

Views: 3195

Answers (2)

Martin Tuskevicius
Martin Tuskevicius

Reputation: 2630

The Scanner class will block whenever the InputStream used to construct it would block. It will usually not block when reading from a file because the contents of it are readily available (i.e., inputStream.available() > 0), they are on your machine after all. However, if you construct a Scanner using an InputStream that may require waiting for data to arrive (e.g., reading text from a remote client, waiting for a page to load so you can read its source, etc.) then Scanner#nextLine() will block because it needs to wait for enough information to build the next line to arrive.

Upvotes: 3

user207421
user207421

Reputation: 310980

It blocks if it's reading from a network and there is no data or no newline present in the input and it hasn't reached EOS. You must be reading from a file.

Upvotes: 0

Related Questions