elahe
elahe

Reputation: 11

IOUtils.ToByteArray(InputStream) is thread safe?

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?

Upvotes: 0

Views: 785

Answers (1)

LppEdd
LppEdd

Reputation: 21134

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

Upvotes: 3

Related Questions