Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best resizable byte buffer available in Java?

Tags:

java

I need a byte buffer class in Java for single-threaded use. The buffer should resize when it's full, rather than throw an exception or something. Very important issue for me is performance.

What would you recommend?

ADDED: At the momement I use ByteBuffer but it cannot resize. I need one that can resize.

like image 385
Worker Avatar asked Jun 13 '11 10:06

Worker


People also ask

What is Java byte buffer?

ByteBuffer holds a sequence of integer values to be used in an I/O operation. The ByteBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get method that read single bytes. Absolute and relative put methods that write single bytes.

How do you create a byte buffer in Java?

Then, how can we create a direct buffer? A direct ByteBuffer is created by calling the allocateDirect() method with the desired capacity: ByteBuffer buffer = ByteBuffer. allocateDirect(10);

What is ByteBuffer used for?

A ByteBuffer is a buffer which provides for transferring bytes from a source to a destination. In addition to storage like a buffer array, it also provides abstractions such as current position, limit, capacity, etc. A FileChannel is used for transferring data to and from a file to a ByteBuffer.


1 Answers

Any reason not to use the boring normal ByteArrayOutputStream?

As mentioned by miku above, Evan Jones gives a review of different types and shows that it is very application dependent. So without knowing further details it is hard to speculate.

I would start with ByteArrayOutputStream, and only if profiling shows it is your performance bottleneck move to something else. Often when you believe the buffer code is the bottleneck, it will actually be network or other IO - wait until profiling shows you need an optimisation before wasting time finding a replacement.

If you are moving to something else, then other factors you will need to think about:

  • You have said you are using single threaded use, so BAOS's synchronization is not needed
  • what is the buffer being filled by and fed into? If either end is already wired to use Java NIO, then using a direct ByteBuffer is very efficient.
  • Are you using a circular buffer or a plain linear buffer? If you are then the Ostermiller Utils are pretty efficient, and GPL'd
like image 172
Nick Fortescue Avatar answered Oct 06 '22 14:10

Nick Fortescue