private static Unsafe unsafe;
private static boolean AVAILABLE = false;
static {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe)field.get(null);
AVAILABLE = true;
} catch(Exception e) {
// NOOP: throw exception later when allocating memory
}
}
public static boolean isAvailable() {
return AVAILABLE;
}
private static Direct INSTANCE = null;
public static Memory getInstance() {
if (INSTANCE == null) {
INSTANCE = new Direct();
}
return INSTANCE;
}
private Direct() {
}
@Override
public long alloc(long size) {
if (!AVAILABLE) {
throw new IllegalStateException("sun.misc.Unsafe is not accessible!");
}
return unsafe.allocateMemory(size);
}
@Override
public void free(long address) {
unsafe.freeMemory(address);
}
@Override
public final long getLong(long address) {
return unsafe.getLong(address);
}
@Override
public final void putLong(long address, long value) {
unsafe.putLong(address, value);
}
@Override
public final int getInt(long address) {
return unsafe.getInt(address);
}
@Override
public final void putInt(long address, int value) {
unsafe.putInt(address, value);
}
}
在本地内存中分配一个对象
让我们来将下面的Java对象放到本地内存中:
public class SomeObject {
private long someLong;
private int someInt;
public long getSomeLong() {
return someLong;
}
public void setSomeLong(long someLong) {
this.someLong = someLong;
}
public int getSomeInt() {
return someInt;
}
public void setSomeInt(int someInt) {
this.someInt = someInt;
}
}
我们所做的仅仅是把对象的属性放入到Memory中:
public class SomeMemoryObject {
private final static int someLong_OFFSET = 0;
private final static int someInt_OFFSET = 8;
private final static int SIZE = 8 + 4; // one long + one int
private long address;
private final Memory memory;