Reading and writing primitive arrays to a NIO buffer: wrapper buffers

The ByteBuffer class is convenient for reading and writing arrays of byte, or for reading and writing individual values of other types (ints, floats etc). For reading and writing an array of these other types, various typed buffer classes are available. For example:

Each of these classes has an allocate() method. However, we can also create a view of an existing ByteBuffer. For example, here we create a ByteBuffer and then create an IntBuffer view of that byte buffer in order to read and write multiple ints to the buffer:

    ByteBuffer b = ByteBuffer.allocate(50);
    IntBuffer ib = b.asIntBuffer();
    int[] data = {100, 200, 300};

Note that b and ib are views of the same data. Writing the ints to ib is in effect writing bytes (more efficiently) into b. Using view buffers in this way allows data of different types to be mixed in the same buffer, but still allows efficient reading and writing of multiple items where necessary.

If you're only writing single ints, longs etc, then there's no need to create the buffer view: you can already write any primitive data type to a ByteBuffer with its get() and put() methods.

Performance benefits of wrapper buffers

NIO buffer performance tests suggest that there is around a 20% performance benefit in using a wrapper buffer to write a primitive array to a ByteBuffer.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.