淘先锋技术网

首页 1 2 3 4 5 6 7

这让我感到惊讶,我正在玩

Java Unsafe.基本上我正在测试的是

Allocate unsafe memory -> free the memory -> Write to the freed memory

当我访问被释放的内存时,我期待看到某种分段错误错误,但令人惊讶的是,没有引发错误/异常.

我的代码是:

protected static final Unsafe UNSAFE;

static {

try {

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

field.setAccessible(true);

UNSAFE = (Unsafe) field.get(null);

} catch (Exception e) {

throw new RuntimeException(e);

}

}

@Test

public void test() {

long ptr = UNSAFE.allocateMemory(1000);

UNSAFE.freeMemory(ptr);

UNSAFE.putOrderedLong(null, ptr, 100L);

}

我的问题是,如果是这样,为什么我们需要在Unsafe中使用freeMemory()函数?真的是什么?