EDIT:
Highlighting byte [] is much faster than reading from a file or socket, I would be surprised that this will make a big difference if you only have a system in which microseconds cost money.
Reading time of a file with 64 KB is about 10 ms (if only the file is in memory)
The time taken to allocate a 64 KB [] byte is about 0.001 ms, possibly faster.
You can use apache IO IOBuffer, however this is very expensive.
You can also use ByteBuffer, position() will tell you how much data has been read.
If you donβt know how big the buffer is and you have a 64-bit JVM, you can create a large direct buffer. When used, memory will be allocated (per page). As a result, you can allocate 1 GB, but can only use 4 KB if that's all you need. The direct buffer does not support array() , however you will have to read from ByteBuffer using other methods.
Another solution is to use AtomicReference<byte[]> , the called method can increase the size as necessary, but if it is large enough, it will reuse the previous buffer.
source share