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.allocateMemoryreturns alongwhich gets allocated on JVM. Cost is8bytes on JVM for thatlong.int myInteger = 3is first allocated on heap/stack on the JVM. Cost is4bytes on the JVM.unsafe.putIntthen writesmyIntegeroff-heap. Cost is4bytes off-heap.- Reading that
intback out viaunsafe.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?
8bytes forlongaddress on the JVM ?- And I'm allocating that
inttwice, 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.