I'm trying to turn off GC and manage memory by hand in hot pieces of code. Here is what I'm trying to do:
private static Unsafe unsafe = getUnsafe();
//...
long ptr = unsafe.allocateMemory(3);
String s = "abc";
byte[] bts = s.getBytes(); //{97,98,99}
for (int i = 0; i < bts.length; i++) {
unsafe.putByte(ptr + i, bts[i]); // <----------- Here
}
System.out.println(unsafe.getByte(ptr)); //97
System.out.println(unsafe.getByte(ptr + 1)); //98
System.out.println(unsafe.getByte(ptr + 2)); //99
unsafe.freeMemory(ptr);
The program prints the correct result, but I'm not quite sure if I didn't get some undefined behavior here. What I'm trying to do is to store some bytes outside of heap memory and reclaim the memory by hand when we delete this bytes.
The question is if it's correct to do this:
unsafe.putByte(ptr + i, bts[i]); //Just ptr + i
Maybe the memory allocated with Unsafe::allocateMemory
is not sequential or something like that. JavaDoc is not clear about it. Can you help me