Akashic Records

What is the way of Direct Memory Access in Java? 본문

오래된글/Java

What is the way of Direct Memory Access in Java?

Andrew's Akashic Records 2018. 4. 7. 22:53
728x90

Java was initially designed as a safe, managed environment. Nevertheless, Java HotSpot VM contains a “backdoor” that provides a number of low-level operations to manipulate memory and threads directly.

This backdoor class – sun.misc.Unsafe – is widely used by JDK itself in packages like “java.nio” or “java.util.concurrent”. However, using this backdoor is certainly not suggested for use in the production environment, because this API is extremely dangerous, non-portable, and volatile. The Unsafe class provides an easy way to look into HotSpot JVM internals and to do some tricks. Sometimes it can be used to study VM internals without C++ code debugging, sometimes it can be leveraged for profiling and development tools.


How to use ‘sun.misc.Unsafe’

package com.blogspot.daddycat.test;


import java.lang.reflect.Field;


import sun.misc.Unsafe;


public class UnsafeTest {


   public static void main(String... args) {

       Unsafe unsafe = null;


       try {

           Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");

           field.setAccessible(true);

           unsafe = (sun.misc.Unsafe) field.get(null);

       } catch (Exception e) {

           throw new AssertionError(e);

       }


       int ten = 10;

       byte size = 1;

       long mem = unsafe.allocateMemory(size);

       unsafe.putAddress(mem, ten);

       long readValue = unsafe.getAddress(mem);

       System.out.println("Val: " + readValue);


       try {

Object o = unsafe.allocateInstance(java.lang.String.class);

System.out.println("Type: "+o.getClass().getCanonicalName());

} catch (InstantiationException e) {

e.printStackTrace();

}

   }

}


Console log

Val: 10

Type: java.lang.String


728x90

'오래된글 > Java' 카테고리의 다른 글

EJB CMP의 단점  (0) 2018.04.07
Scrolling Result Sets  (0) 2018.04.07
JDBC driver types  (0) 2018.04.07
객체 저장 : Storing Classes, Images and Other Large Objects  (0) 2018.04.07
Easy java Persistence  (0) 2018.04.07
Comments