Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to clear() bytebuffer after allocation?

Tags:

java

I inherited some java code that write messages to a socket using a local ByteBuffer:

public void sendMessage(){
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
    byteBuffer.clear();
    byteBuffer.putInt((int) 128);
}

It seems that the clear() call is unnecessary. Wouldn't allocate be guaranteed to return a freed block of memory?

like image 556
Adam Hughes Avatar asked Dec 25 '22 08:12

Adam Hughes


2 Answers

It is totally unnecessary to call clear() after allocateDirect.

What allocateDirect does is:

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.

What clear does is:

The position is set to zero, the limit is set to the capacity, and the mark is discarded.
[..]
This method does not actually erase the data in the buffer, but it is named as if it did because it will most often be used in situations in which that might as well be the case.

In other words, the state of the ByteBuffer directly after allocation is the same as the state after clear() (ignoring the fact that clear() doesn't reset the elements to zero).

like image 123
Mark Rotteveel Avatar answered Jan 15 '23 17:01

Mark Rotteveel


It is not necessary to clear the buffer if you have not used it yet (and messed up the mark).

Note that any contents in mem is still there even after a call to clear, as it just resets the limit and throws out the current mark.

So the end data area result is the same as for new allocation.

It is however common to always clear a buffer reference you recieve from unknown code, to fill like:

ByteBuffer FillBytes(ByteBuffer buf) 
 { 
    buf.clear();
    //--- 
 }

because even if you may sort of assume the buffer passed to you will be ready for filling, due to the nature of the method contract, you can not assume that the initial dev has reset it prior to your method trying to fill it for instance (may have been used for something already and thus need to be reset).

like image 32
Richard Tyregrim Avatar answered Jan 15 '23 18:01

Richard Tyregrim