Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are direct buffers in Java initialized to a default value like arrays?

When I initialize an array in Java like:

float[] array = new float[1000];

all elements are initialized to 0. Is that also the case when I allocate a direct buffer like this:

FloatBuffer buffer = ByteBuffer.allocateDirect(4*1000).asFloatBuffer();

? I always seem to get only zeroes, but perhaps it's implementation dependent...

like image 541
Se Norm Avatar asked Jul 03 '11 17:07

Se Norm


People also ask

What is a direct buffer Java?

A direct buffer is a chunk of native memory shared with Java from which you can perform a direct read. An instance of DirectByteBuffer can be created using the ByteBuffer. allocateDirect() factory method.

Does Java automatically initialize arrays?

In Java, all array elements are automatically initialized to the default value. For primitive numerical types, that's 0 or 0.0 .

Does Java auto initialize arrays to zero?

By default in Java, data types like int, short, byte, and long arrays are initialized with 0. So, if you create a new array of these types, you don't need to initialize them by zero because it's already their default setting.

How do buffers work Java?

A buffer is essentially a block of memory into which you can write data, which you can then later read again. This memory block is wrapped in a NIO Buffer object, which provides a set of methods that makes it easier to work with the memory block.


2 Answers

It looks like the answer is probably.

Looking at the implementation of ByteBuffer, it uses DirectByteBuffer under the hood. Taking a look at the implementation source code of Android, it has this comment:

Constructs a new direct byte buffer of the given capacity on newly allocated OS memory. The memory will have been zeroed.

So, when you allocate a buffer, all of the memory contents will be initialized to zero. The oracle implementation also does this zeroing.

This is an implementation detail though. Since the javadoc says nothing about the zeroing, it's technically incorrect to rely on it. To be correct, you should really zero the buffer yourself. In practice, if you're really worried about performance for some reason, you could leave it out, but be warned that some implementations of the JVM might not do this zeroing.

like image 188
jterrace Avatar answered Sep 25 '22 03:09

jterrace


Looking at the Javadoc for Java 7 and also Java 8

it now says

The new buffer's position will be zero, its limit will be its capacity, its mark will be undefined, and each of its elements will be initialized to zero. Whether or not it has a backing array is unspecified

So there is no longer any need for you to zero them yourself.

like image 20
Paul Taylor Avatar answered Sep 23 '22 03:09

Paul Taylor