开发者

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

开发者 https://www.devze.com 2023-03-16 20:41 出处:网络
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:

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...


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.


From the ducmentation to the parent abstract class Buffer:

The initial content of a buffer is, in general, undefined.

In the absence of anything to the contrary, I would assume that this applies to buffers allocated by ByteBuffer.allocateDirect(). Interestingly, I suppose that strictly it applies to ordinary array-backed buffers as well, though it is implicit in the allocation of a Java array that the array will be zeroed.


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.


There is no way to tell so the question is futile. The initial position are zero so there is no API you can execute that will return a part of the buffer at hasn't been 'put' to yet.

0

精彩评论

暂无评论...
验证码 换一张
取 消