2013년 11월 29일 금요일

What is the way of Direct Memory Access in Java?

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

댓글 없음:

댓글 쓰기

ETL 솔루션 환경

ETL 솔루션 환경 하둡은 대용량 데이터를 값싸고 빠르게 분석할 수 있는 길을 만들어줬다. 통계분석 엔진인 “R”역시 하둡 못지 않게 관심을 받고 있다. 빅데이터 역시 데이터라는 점을 볼때 분산처리와 분석 그 이전에 데이터 품질 등 데이...