allocateMemory() Method on Direct Memory

This section provides a tutorial example to show allocate memory from the Direct Memory data area using the allocateMemory() method from the sun.misc.Unsafe class.

chaofanwei provides a different way to access the Direct Memory area using the sun.misc.Unsafe class in a sample program at http://blog.csdn.net/chaofanwei/article/details/19483101.

Here is revised version of the sample program, DirectMemoryUnsafeAllocation.java:

/* DirectMemoryUnsafeAllocation.java
 * Based on a sample program from chaofanwei at
 * http://blog.csdn.net/chaofanwei/article/details/19483101
 */
import java.lang.reflect.Field;  
import sun.misc.Unsafe; 
class DirectMemoryUnsafeAllocation {
   private static final int _10MB = 10*1024*1024;  
   public static void main(String[] args) throws Exception {  
      Field unsafeField = Unsafe.class.getDeclaredFields()[0];  
      unsafeField.setAccessible(true);  
      Unsafe unsafe = (Unsafe) unsafeField.get(null);  

      int max = 1000;
      long[] arr = new long[max];
      heapCheck();
      for (int n=0; n<max; n++) {
         arr[n] = unsafe.allocateMemory(_10MB);
//         unsafe.freeMemory(arr[n]);
         System.out.println((n+1)+": "
            +((n+1)*10)+" MB of objects created.");
         heapCheck();
      }
   }
   public static void heapCheck() {
      Runtime rt = Runtime.getRuntime();
      rt.gc();
      long total = rt.totalMemory();
      long free = rt.freeMemory();
      long used = total - free;
      java.io.Console con = System.console();
      con.format("Total memory: %s%n",total);
      con.format(" Free memory: %s%n",free);
      con.format(" Used memory: %s%n",used);
      String str = con.readLine("Press ENTER key to continue: ");
   }
}

Compile and run with HotSpot JVM 1.8:

C:\herong>\progra~1\java\jdk1.8.0\bin\javac 
   DirectMemoryUnsafeAllocation.java

DirectMemoryUnsafeAllocation.java:6: warning: Unsafe is internal 
   proprietary API and may be removed in a future release
import sun.misc.Unsafe;
               ^
DirectMemoryUnsafeAllocation.java:10: warning: Unsafe is internal 
   proprietary API and may be removed in a future release
      Field unsafeField = Unsafe.class.getDeclaredFields()[0];
...                          ^
                       ^
C:\herong>\progra~1\java\jdk1.8.0\bin\java 
   DirectMemoryUnsafeAllocation

Total memory: 16318464
 Free memory: 16051712
 Used memory: 266752
Press ENTER key to continue:
(tasklist output: java.exe   7744 Console   1   14,924 K)

1: 10 MB of objects created.
Total memory: 16318464
 Free memory: 16020136
 Used memory: 298328
Press ENTER key to continue:
(tasklist output: java.exe   7744 Console   1   15,004 K)

2: 20 MB of objects created.
Total memory: 16318464
 Free memory: 16020136
 Used memory: 298328
Press ENTER key to continue:
(tasklist output: java.exe   7744 Console   1   15,012 K)

3: 30 MB of objects created.
Total memory: 16318464
 Free memory: 16044096
 Used memory: 274368
Press ENTER key to continue:
(tasklist output: java.exe   7744 Console   1   15,020 K)

...
160: 1600 MB of objects created.
Total memory: 16318464
 Free memory: 16043664
 Used memory: 274800
Press ENTER key to continue:
(tasklist output: java.exe   7744 Console   1   16,448 K)

Exception in thread "main" java.lang.OutOfMemoryError
   at sun.misc.Unsafe.allocateMemory(Native Method)
   at DirectMemoryUnsafeAllocation.main(DirectMemoryUnsafeAllocation.java:18)

We have some interesting result here:

Of course, the Unsafe class is not safe, so do not use it unless you absolutely have to. For more information on the Unsafe class, read the javadoc at http://www.docjar.com/docs/api/sun/misc/Unsafe.html.

Last update: 2014.

Table of Contents

 About This Book

 Downloading and Installing JDK 1.8.0 on Windows

 Downloading and Installing JDK 1.7.0 on Windows

 java.lang.Runtime Class - The JVM Instance

 java.lang.System Class - The Operating System

 ClassLoader Class - Class Loaders

 Class Class - Class Reflections

 Sun's JVM - Java HotSpot VM

 JRockit JVM 28.2.7 by Oracle Corporation

JVM Runtime Data Areas

 What Are Runtime Data Areas?

 Method Area Expansion Demonstration

 OutOfMemoryError on the Method Area

 Method Area Growth with Dynamically Generated Classes

 Garbage Collection Issue with Dynamically Generated Classes

 Interned Strings Stored in Heap

 Heap Expansion Demonstration

 Direct Memory Expansion Demonstration

allocateMemory() Method on Direct Memory

 JVM Stack Expansion Demonstration

 PC Register and Native Method Stack

 Memory Management and Garbage Collectors

 Garbage Collection Tests

 JVM Stack, Frame and Stack Overflow

 Thread Testing Program and Result

 CPU Impact of Multi-Thread Applications

 I/O Impact of Multi-Thread Applications

 CDS (Class Data Sharing)

 Micro Benchmark Runner and JVM Options

 Micro Benchmark Tests on "int" Operations

 Micro Benchmark Tests on "long" Operations

 Micro Benchmark Tests in JIT Compilation Mode

 Micro Benchmark Tests on "float" and "double" Operations

 Outdated Tutorials

 References

 PDF Printing Version