Are direct buffers in Java initialized to a default value, such as an array?

When I initialize an array in Java, for example:

float[] array = new float[1000]; 

all elements are initialized to 0. This is also the case when I allocate a direct buffer as follows:

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

? I always get only zeros, but maybe it depends on the implementation ...

+8
java initialization buffer
source share
4 answers

From ducmentation to the parent abstract class Buffer:

The original contents of the buffer are generally undefined .

In the absence of anything the other way around, I would suggest that this applies to the buffers allocated by ByteBuffer.allocateDirect (). Interestingly, I believe that this strictly applies to regular buffers with array support, although it is implied in the distribution of the Java array that the array will be nullified.

+3
source share

It seems like an answer is possible .

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

Creates a new direct byte buffer a given potential over the newly allocated OS memory. The memory will be reset to zero.

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

However, this is an implementation detail. Since javadoc says nothing about zeroing, it is technically incorrect to rely on it. To be true, you must really flush the buffer yourself. In practice, if for some reason you are really worried about performance, you can leave it, but be careful that some JVM implementations may not do this reset.

+4
source share

Looking for Javadoc for Java 7 as well as Java 8

now he says

The new buffer position will be zero, its limit will be equal to capacity, its mark will be undefined, and each of its elements will be initialized to zero. Regardless of whether it has a base array is not defined

Thus, you no longer need to reset them yourself.

+1
source share

It is impossible to say that the question is useless. The starting position is zero, so the API cannot be executed, which will return part of the buffer until it has been marked.

0
source share

All Articles