Wrapping InputStream for non-blocking ReadableByteChannel
You can try to implement such a pipe yourself using "Inputstream.avalable ()" to avoid blocking. However, this method is not guaranteed to return the correct value, so you need to check the Inputstream implementation you are using.
Are you sure you need a non-blocking channel? Typically, a periodic poll is required to verify that data has arrived. Asynchronous pipes that call callbacks when data arrives make more sense.
source to share
ReadableByteChannel.newChannel method
public static ReadableByteChannel newChannel(final InputStream in) {
checkNotNull(in, "in");
if (in instanceof FileInputStream &&
FileInputStream.class.equals(in.getClass())) {
return ((FileInputStream)in).getChannel();
}
return new ReadableByteChannelImpl(in);
}
and the reading method ReadableByteChannelImpl
public int read(ByteBuffer dst) throws IOException {
int len = dst.remaining();
int totalRead = 0;
int bytesRead = 0;
synchronized (readLock) {
while (totalRead < len) {
int bytesToRead = Math.min((len - totalRead),
TRANSFER_SIZE);
if (buf.length < bytesToRead)
buf = new byte[bytesToRead];
if ((totalRead > 0) && !(in.available() > 0))
break; // block at most once
try {
begin();
bytesRead = in.read(buf, 0, bytesToRead);
} finally {
end(bytesRead > 0);
}
if (bytesRead < 0)
break;
else
totalRead += bytesRead;
dst.put(buf, 0, bytesRead);
}
if ((bytesRead < 0) && (totalRead == 0))
return -1;
return totalRead;
}
}
so it just calls the InputStream read method and the javadoc of the Inputstream read method:
This method blocks until input is available, end of file is detected, or an exception is thrown.
so that you can implement a subclass of InputStream and override the read methods and implement the methods as non-blocking.
source to share
ReadableByteChannel readableChannel = Channels.newChannel(InputStream in)
http://docs.oracle.com/javase/7/docs/api/java/nio/channels/Channels.html
source to share