Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast erase (not clear) a ByteBuffer in Java

I am trying to "clean up" a ByteBuffer to be all zero bytes (all 0x00). I tried to loop over all positions in the buffer and set them to 0x00, but the efficiency is bad. Is there any better way to quickly clear a ByteBuffer - similar to what BitSet.clear() does?

Please note that ByteBuffer.clear() is not an appropriate solution for me in this scenario--I have to erase all the data inside of the buffer, and not just reset the pointer to the beginning.

Any hints?

Edit: the ByteBuffer is used as a part of the hash table, and it maintains the references of the hash table entries. Every time when the hash table needs to be flushed, I have to reset the hash table entries for later hash table insertion. Since the hash table is accessed in a random-fashion, I cannot simply clear() the state of the byte buffer.

like image 508
asksw0rder Avatar asked Jun 25 '12 21:06

asksw0rder


People also ask

How to clear ByteBuffer in Java?

The clear() method of java. nio. ByteBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded.

Why use ByteBuffer?

ByteBuffer is useful for binary conversion of data to and from Java primitive data. For instance suppose you want to convert an integer to an array of bytes. The following shows an integer and the hex value of the bytes. To convert the integer to a byte array, you can use the ByteBuffer as folows.

What is the difference between the methods Clear () and rewind () from the Java NIO buffer class?

Note that in JDK document's words rewind() and clear() looks alike for "cleaning" the ByteBuffer . Actually the old data exists, furthermore rewind() should be used before channel-write or get operation and clear() corresponds to channel-read or put operation.

What does ByteBuffer rewind do?

ByteBuffer rewind() methods in Java with Examples ByteBuffer Class is used to rewind this buffer. The position is set to zero and the mark is discarded. Invoke this method before a sequence of channel-write or get operations, assuming that the limit has already been set appropriately.


1 Answers

Have you tried using one of the ByteBuffer.put(byte[]) or ByteBuffer.put(ByteBuffer) methods to write multiple zeros in one go? You could then iterate over the buffer in chunks of 100 or 1000 bytes, or whatever, using an array or buffer pre-filled with zeros.

Downside: this is an optional operation, so not all implementations of ByteBuffer are required to provide it...

like image 151
DNA Avatar answered Sep 20 '22 17:09

DNA