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

댓글 없음:

댓글 쓰기

시스템 부팅시 도커 컨테이너 자동 실행

Docker 컨테이너를 운용중인 시스템이 Reboot 되버리면 컨테이너가 자동으로 올라오지 않아 불편해서 시스템 리붓시 컨테이너를 자동으로 시작되게 init 데몬에 등록하기로 했습니다. 서버는 Ubuntu 17.10 Docker는 17.0...