Wrapping InputStream for non-blocking ReadableByteChannel

Is it possible to create a non-blocking ReadableByteChannel from an InputStream object?

Channel.newChannel (inputStream) - creates a channel that can be blocked by a blocked call to InputStream.read

+4


source to share


4 answers


No, It is Immpossible. See the Javadoc .



+1


source


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.

+1


source


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.

0


source


ReadableByteChannel readableChannel  = Channels.newChannel(InputStream in)

      

http://docs.oracle.com/javase/7/docs/api/java/nio/channels/Channels.html

see fooobar.com/questions/892289 / ...

-1


source







All Articles