IOUtils.ToByteArray(InputStream) is thread safe?

716 Views Asked by At

Can using IOUtils.ToByteArray leads to concurrency problems?

private byte[] saveLetterContent(InputStream input) {
  ...

  byte[] letterContent = IOUtils.toByteArray(input);

  ...
}

I mean is it possible that letterContent in this method change incorrectly because of concurrency?

1

There are 1 best solutions below

5
On

I mean is it possible that letterContent in this method change incorrectly because of concurrency?

Absolutely, calling toByteArray(InputStream) without guarding the inputted InputStream can lead to undefined behavior. It is also easily demonstrable.

final String value = "hello! ciao!";
final byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);
System.out.println(valueBytes.length);

final ByteArrayInputStream is = new ByteArrayInputStream(valueBytes);

new Thread(() -> {
   try {
      is.read(new byte[10]);
   } catch (final IOException e) {
      //
   }
}).start();

// Thread.sleep(50)

final byte[] bytes = IOUtils.toByteArray(is);
System.out.println(bytes.length);

With the above example, you'll surely notice the second System.out will print a lower bytes length than the first one. You can even play with Thread.sleep and see what happens.

enter image description here