简体   繁体   中英

Wrapping InputStream to non blocking ReadableByteChannel

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

Channel.newChannel(inputStream) - produces channel which could be blocked by blocked InputStream.read invocation

You may try to implement such a channel yourself, using 'Inputstream.avalable()' to avoid blocking. However, this method does not guarantee to return correct value, so you have to check the Inputstream implementation you use.

Are you sure you need non-blocking channel? Generally, it requires periodical polling to check arrival of data. Asynchronous channels, which invoke callbacks on data arrival, have more sense.

No it is not possible. See the Javadoc .

The 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 read method of 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's just calling the read method of the InputStream, and the javadoc of the Inputstream's read method:

This method blocks until input data is available, end of file is detected, or an exception is thrown.

so you can implements a subclass of InputStream and override the read methods, and implement the methods as nonblocking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM