Reputation: 1399
So I've read a few articles around but essentially since I want a fast I/O, I want to write a double array to a file. To do that I need to convert it to a byte array. Unfortunately this makes copying of data.
So I was wondering suing java Unsafe is it possible to make a byte[] variable which points to the address of the double[] array and just interpret the data as bytes rather than doubles? I did not manage to find anywhere so far such example, only again how to use copying memory in order to do this. Any advices are appreciated!
Upvotes: 2
Views: 635
Reputation: 533492
If you start with a ByteBuffer you can hold it's reference and use them interchangably.
ByteBuffer bb = ByteBuffer.allocateDirect(8 * n_doubles);
DoubleBuffer db = bb.asDoubleBuffer();
You can not read/write to either and view it as byte
s or double
s as the same memory is used.
If you want to avoid additional copies to a file, you can use a memory mapped region.
BTW: ByteBuffer uses Unsafe, but in a way which protects you.
Upvotes: 4