James.T
James.T

Reputation: 11

What unsafe.allocateMemory Returns in Java

I was calling the function "unsafe.allocateMemory" for a bulk of Memory from off-heap. But the value returned is odd.

The run-time environment shows here:

Here is my code:

import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class UnsafeTest{
    public static void main(String[] args){
            try{
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            Unsafe unsafe = (Unsafe) theUnsafe.get(null);
            long addr = unsafe.allocateMemory(16);
            System.out.println("the address is :"+addr);
            unsafe.freeMemory(addr);
            }catch(Exception e){
                    System.out.println(e.getMessage());
            }
    }
}

Result:

I thought something's wrong, because the outcome value is so much bigger than the total memory size(about 6G). I wonder if the value was a memory address ? If so, how could it be allocated as there are not so much memory actually. If not, what the base address of the memory/heap in OS.

Upvotes: 1

Views: 3469

Answers (1)

anttix
anttix

Reputation: 7779

Unsafe#allocateMemory returns something called a "native pointer" which is essentially an address in a virtual memory space associated with the JVM process. The operating system and a Memory Management Unit built into the CPU will be responsible of mapping addresses in this virtual space to addresses in real physical memory.

Because the address space is virtual, the numeric value within it has nothing to do with how much physical memory is available to the system: VM layout and addresses returned from memory allocation functions are at the discretion of the operating system and its core libraries that Java depends on. The OS must also consider hardware limitations imposed on the virtual address space.

See also:

Credits: Comments left by @sotirios-delimanolis and @klitos-kyriacou

Upvotes: 2

Related Questions