Re: Making System.in interruptible, how?
On 2/21/2012 9:18 AM, Jan Burse wrote:
Found the following nice article, highlighting how
it would be possible to make System.in interrupible:
http://www.javaspecialists.eu/archive/Issue153.html
Is this the preferred way to do? i.e. to use some
polling, or are there other ways around?
I am not too comfortable with that code.
It seems to work on Windows with 64 bit SUN Java 1.6.
May guess is that it will work in most other contexts.
But is it required to work?
The core logic in the code is:
while (!br.ready()) {
Thread.sleep(200);
}
The docs says:
<doc>
BufferedReader ready
Tells whether this stream is ready to be read. A buffered character
stream is ready if the buffer is not empty, or if the underlying
character stream is ready.
....
True if the next read() is guaranteed not to block for input, false
otherwise. Note that returning false does not guarantee that the next
read will block.
InputStreamReader ready
Tells whether this stream is ready to be read. An InputStreamReader is
ready if its input buffer is not empty, or if bytes are available to be
read from the underlying byte stream.
....
True if the next read() is guaranteed not to block for input, false
otherwise. Note that returning false does not guarantee that the next
read will block.
InputStream available
Returns an estimate of the number of bytes that can be read (or skipped
over) from this input stream without blocking by the next invocation of
a method for this input stream. The next invocation might be the same
thread or another thread. A single read or skip of this many bytes will
not block, but may read or skip fewer bytes.
Note that while some implementations of InputStream will return the
total number of bytes in the stream, many will not. It is never correct
to use the return value of this method to allocate a buffer intended to
hold all data in this stream.
....
an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking or 0 when it reaches the end of
the input stream.
</doc>
It is not clear to me that:
1) System.in.available will in fact return a reliable number
("estimate" sounds a bit flexible)
2) BufferedReader ready will only return true if a full line
is available and not eat any characters if that is not the case
I would seriously consider writing some JNI to do what is necessary on
the relevant platforms.
It is not portable, but at least it is obvious how it works.
Arne