0

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

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 5
    judging by the symbol of your avatar, you are a C++ guy, and you are not just trying to work with java, but actually trying to make java work better. My recommendation is to not even try. Java is pretty good at managing memory, and most chances you are not going to improve anything, only make things worse. – Mike Nakis Aug 08 '17 at 16:06
  • @MikeNakis So you would advice not to use `Unsafe` ever? – St.Antario Aug 08 '17 at 16:07
  • 4
    No, it is never bad to experiment with things, play with it if you like, but be prepared to be surprised by how futile it is to "work against the system". I would use `unsafe` if I was interfacing with external code, writing a device driver, that kind of stuff. I would not use it with the goal of optimizing things. But by all means, toy with it. – Mike Nakis Aug 08 '17 at 16:09

0 Answers0