Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Dec 8, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

non-blocking read

How do I control blocking in Java.

For example, in telnet I would like to take an action if the user presses a certain key. This requires non-blocking read; I think?

It is not currently possible in Java to set an arbitrary stream to be non-blocking as you would with a call like fcntl(fd, F_SETFL, O_NONBLOCK) in Unix. However, there are a few ways of dealing with this, none of which are entirely satisfactory.

If you are dealing with an InputStream, you can check its available() method before reading from it. The available() method will return the number of bytes that can be read from the stream without blocking. The problem with this is that you can't count on every subclass of InputStream to implement available() properly. For example, in JDK 1.1.3, the PushbackInputStream class has an incorrectly implemented available() method. This may have been fixed in the latest JDK by the time you read this.

If you are dealing with a Reader subclass, you can check its ready() method. The ready() method will simply return true if you can read at least one character from it without blocking. Since you don't know how many characters you can read without blocking, you are forced to write rather inefficient code that reads one character at a time, checking ready() before every read. You also still have the problem of possibly unreliable implementations of ready().

If you do not want to block indefinitely while reading from a socket's input stream, you can set a timeout on the socket using the java.net.Socket setSoTimeout() method, which takes an integer representing the maximum number of milliseconds to block on a read. A read from a socket is supposed to throw an InterruptedIOException, but from experience I know that in practice it will also throw a SocketException. To detect the timeout, you have to catch both of these exceptions.

However, you seem to be asking about how to deal with user input from standard input. There is no effective way of reading a character at a time from standard input without writing native code to disable command shell line buffering. In your telnet client example, you would want to create an AWT component from which you would interpret user input by detecting a KeyEvent of type KeyEvent.KEY_PRESSED rather than reading from standard input.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date