Is it "safe" to have a ByteBuffer
and a ByteArrayInputStream
share an underlying byte []
as long they only read from it? If I read/get from one and then the other, since each has their own internal marks/counters etc., is there a possibility of a conflict?
Asked
Active
Viewed 582 times
1

user3416961
- 31
- 3
2 Answers
2
Judging from the source of ByteBuffer.wrap
and ByteArrayInputStream
's constructor, it looks like both classes would store the array that you pass them without making a copy. It also appears that neither class would modify the array, making it safe to share the same byte[]
array across multiple instances of ByteBuffer
and ByteArrayInputStream
.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
1
It is safe, with one caveat. There must be a happens before chain to ensure that the threads using the shared byte[]
can see the last write to the byte[]
prior to it becoming "effectively immutable".
In simple terms, the threads need to synchronize when setting up the sharing,

Stephen C
- 698,415
- 94
- 811
- 1,216
-
OP didn't ask about multi-threading, but perhaps they should have. – markspace Mar 12 '17 at 14:28
-
Well ... to my mind ... "safe" includes all kinds of safety, including thread safety. As I read it, they are asking about thread safety, among other things. – Stephen C Mar 12 '17 at 14:30
-
The part of the code I'm using this in is sequential, but thanks for the heads up re: thread safety. I originally meant only in terms of somehow modifying the underlying `byte []` – user3416961 Mar 12 '17 at 14:34