0

Trying to find solution to read all bytes from InputStream in non blocking mode. Section inputStream.read() in function below blocks forever when no data are available.

private static String extract(InputStream inputStream) throws IOException { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();               
    byte[] buffer = new byte[1024];
    int read = 0;
    while ((read = inputStream.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, read);
    }       
    baos.flush();       
    return  new String(baos.toByteArray(), "UTF-8");
}

How to read all bytes without blocking?

vico
  • 17,051
  • 45
  • 159
  • 315
  • You have tried IOUtils.toString(inputstream)? – Egeo Jun 07 '19 at 07:18
  • 2
    It;s not possible to read from `InputStream` in non-blocking mode. You'll have to use buffer-oriented IO, instead of stream-oriented. Check out the NIO package – Svetlin Zarev Jun 07 '19 at 07:20
  • 1
    You can't read *any* bytes without the risk of blocking. Your question embodies a contradiction in terms. `InputStream` *is* blocking, period. But if you want to 'read all bytes' why do you think you need non-blocking mode? – user207421 Jun 07 '19 at 07:30

1 Answers1

0

I assume you want a timeout for reading.

For an URLConnection (should the InputStream stem from that) you can set miscellaneous timeouts, and check the optimal blocksize (that from the sender).

For Sockets the same functionality exists.

A timeout one can make oneself using a thread: this I found on SO.

But also Future seems appropriate:

ExecutorService service = Executors.newFixedThreadPool(2); // Or whatever.
// Callable<String> callable = () -> extract(inputStream);
Future<String> future = service.submit(() -> extract(inputStream));
try {
    String s = future.get(3, TimeUnit.SECONDS);
} catch (Exception e){
    e.printStackTrace();
    future.cancel(true);
    inputStream.close();
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • He wants to read all bytes, so why would he need a timeout? or indeed non-blocking mode? – user207421 Jun 07 '19 at 08:08
  • @user207421 "blocks forever when no data available" - it looks like he want to prevent that. My proposed solution: a reasonable timeout on the operation. And yes, then you have no data at all. BTW as this is a future, you can submit the task already as early as possible, and at the moment of the get maybe even have a 0 response time. – Joop Eggen Jun 07 '19 at 08:30