December 31st, 2008
Ten amazing java applications
December 27th, 2008
Java에서 직접 allocation/deallocation 시키기
백년만의 기술 포스팅인듯.
오늘 내용은 사실 자바에 관한 내용이라기 보다는 Sun JVM에 종속적인 내용이다.
딱히 권장할 만한 내용은 아니니 듣고도 모르는척 하자.
Sun VM과 그의 변종들은 이름만으로도 호기심을 유발시키는 Unsafe라는 클래스가 있다.
public 클래스 이지만 bootstrap classloader를 통한 클래스에서만 사용 가능하게 처리되어 있지만 간단하게 workaround 가능하다.
다음 두 메소드를 통해 heap외부의 메모리를 직접 할당/해제 가능하다.
JAVA:
-
public native long allocateMemory(long bytes);
-
public native void freeMemory(long address);
다음은 간단한 예제이다.
GC가 원하는 대로 말을 잘 안듣는데 지쳐있을때 빠지기 쉬운 나쁜길이라 할까.
JAVA:
-
package net.hanjava.benchmark;
-
-
import java.lang.reflect.Field;
-
-
import sun.misc.Unsafe;
-
-
public class NativeAllocationTest {
-
private static Unsafe unsafe = null;
-
-
private static Unsafe getUnsafe() {
-
if (unsafe == null) {
-
try {
-
fieldUnsafe.setAccessible(true);
-
unsafe = (Unsafe) objUnsafe;
-
}
-
}
-
return unsafe;
-
}
-
-
long addr = getUnsafe().allocateMemory(1024 * 1024 * 1024); // 1024 MiB
-
for (byte i = 0; i <100; i++) {
-
getUnsafe().putByte(null, addr + i, i);
-
}
-
-
for (byte i = 0; i <100; i++) {
-
byte v = getUnsafe().getByte(null, addr + i);
-
}
-
getUnsafe().freeMemory(addr);
-
}
-
}