Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from Java standard input without polling or constantly reading and without wasting resources [closed]

Tags:

java

If a program sends data to my standard input stream in Java through a pipe, how can I make my Java program atuomatically detect if new data is coming through the pipe into the input stream so that I can read it?

I know that I could use an infinite while loop that constantly keeps reading and checking the standard input stream. But this is inefficent and it takes a lot of resources. I am not even allowed to do this for my assignment.

It has to be synchronized somehow. Can I put a listener on the pipe or standard input that says: "Hey! Read the standard input now! New data is coming!" or can I make the pipe send interrupts or how do I do this?

like image 975
user2726067 Avatar asked Oct 21 '22 16:10

user2726067


2 Answers

As others have said, there is no way to check to see if input is available from an InputStream (or Reader) that doesn't either block the current thread ... or involve expensive polling.

The simple solution is just to attempt the read, and block until data arrives. This solution is OK unless ...

  • you want to do other things while waiting for the data to arrive, or
  • the data might arrive on one of many input streams.

In such cases, you either need to use NIO selectors (which allow you to wait until data arrives on one of a set of streams, or use a different thread for reading the data from each stream, and other threads for processing it (or doing other things). In the latter case, you probably need some kind of queueing mechanism to pass "messages" from the reader thread / threads to the processing thread / threads.

However, the bottom line is that we can't offer a good concrete solution without more details of your application.


One piece of advice: don't try to use the InputStream.available() or Reader.ready(). These involve polling ... and their specified semantics are such that that can't tell you definitively if a read will block. They are basically useless ...

like image 176
Stephen C Avatar answered Nov 03 '22 07:11

Stephen C


The standard way to do this is to use the read method on the inputstream? If the data is text then you may use the readLine method.

See this informative link

Of course, the tread that is calling this code will block, so it would ideally this code would be in a different thread.

like image 42
Scary Wombat Avatar answered Nov 03 '22 08:11

Scary Wombat