0

I am struggling from few days to find out exact answer for this. How to clear out bytebuffer in a correct way in Java.

I need to make sure that in main memory no one can see the byte value after processing.

I did not find any built-in method from Java class which will achieve this result.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
5125
  • 13
  • 1
  • How about `Arrays.fill()`. You must have not been looking very hard. – Kayaman Sep 02 '23 at 09:58
  • This is what I found. was more keen on how do I clear out the space than fill operations. But thanks. – 5125 Sep 02 '23 at 10:11
  • If you don't understand that filling with zero is the same as "clearing out", then you're not much of a programmer. – Kayaman Sep 02 '23 at 10:26
  • `fill` with zero -> "*no one can see the byte value*", as requested in question -- "*more keen on how do I clear out the space*" -> memory usage goes down, **but** the bytes are not really *gone*, the data maybe still there -- you must decide which one you want (as requested in question, or as in the comment) well, you can do both (first fill, then free the space) || BTW "*seems arrays.fill is the only way.*" - you can also fill the buffer with random data, or whatever; just bit more code – user22471702 Sep 02 '23 at 10:47
  • 1
    Are we talking about an array or about `java.nio.ByteBuffer`? – Mark Rotteveel Sep 02 '23 at 11:06

1 Answers1

0

Extending on Kayamans answer. Arrays.fill() is the way to go. The idea here is you will fill the bytebuffer with (byte)0 which will make it impossible to read the origin bytes once fill is invoked.

Other than this we cannot clear out space using any inbuilt method.

What we are doing is substitution rather than clearing out or freeing the space.

Hope this helps.

More read: Are byte arrays initialised to zero in Java?

linden
  • 16
  • 1
  • 1
    Seems arrays.fill is the only way. we cannot freeup the space by default right? – 5125 Sep 02 '23 at 10:12
  • You fill with zero, then you null out the reference. That way the data is not visible while it's waiting for GC. – Kayaman Sep 02 '23 at 10:27