Cost of calling `sun.misc.Unsafe` functions in Java?

Viewed 65

I'm trying to understand the cost of allocating memory off-heap in Java using Unsafe.

//This is how I created an Unsafe instance
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);

Please help me understand memory allocations in the following code that writes an int (4 bytes) off-heap.

long address = unsafe.allocateMemory(Integer.BYTES);
int myInteger = 3;
unsafe.putInt(address, myInteger);
int myReadInt = unsafe.getInt(address);

Cost

  • unsafe.allocateMemory returns a long which gets allocated on JVM. Cost is 8 bytes on JVM for that long.
  • int myInteger = 3 is first allocated on heap/stack on the JVM. Cost is 4 bytes on the JVM.
  • unsafe.putInt then writes myInteger off-heap. Cost is 4 bytes off-heap.
  • Reading that int back out via unsafe.getInt, I'm copying that off-heap allocation into JVM which another JVM allocation?

So to write 4 bytes of memory off-heap. I'm allocating 16 bytes in total?

  • 8 bytes for long address on the JVM ?
  • And I'm allocating that int twice, once on the JVM and then off-heap?

Am I correct to understand that on the JVM I'm allocating twice as much memory to go off-heap? In C or C++, this would not be the case?

And to read the integer back out from off-heap, I'm copying that memory back into JVM, which now has to be garbage collected?

If I passed myInteger = 3 directly to the function, would it by any chance skip the int allocation on JVM?

unsafe.putInt(address, 3);

Edit: As pointed out by Joachim in the comments, stack allocation is efficient. The question is more about cost of total memory allocation instead of efficiency, that int could be replaced with some Object that is heap allocated or something that is a lot larger than 4 bytes.

0 Answers
Related