This did surprise me, I'm playing with Java Unsafe. Basically what I am testing is
Allocate unsafe memory -> free the memory -> Write to the freed memory
I was expecting to see some kind of segmentation fault error as I am accessing memory that was freed, but surprisingly, no error / exception was raised.
My code is:
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);
}
My question is, if so then why do we need the freeMemory()
function in Unsafe? What is it really for?
Heap-memory is accessible or exists as long as the whole application(or java program) runs.
Off-heap memory offloads values to a storage area that is not subject to Java GC. By taking advantage of off-heap storage, an application can reduce the amount of heap storage that is subject to GC overhead. Off-heap memory works in conjunction with the heap, it does not replace it.
The off-heap store extends the in-memory store to memory outside the of the object heap. This store, which is not subject to Java garbage collection (GC), is limited only by the amount of RAM available. Because off-heap data is stored in bytes, only data that is Serializable is suitable for the off-heap store.
OutOfMemoryError is a runtime error in Java which occurs when the Java Virtual Machine (JVM) is unable to allocate an object due to insufficient space in the Java heap. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java. lang.
You only get a signal if you either read addresses which hasn't been assigned a page or write to memory which is read only or not assigned a page.
When you allocate small regions of memory it takes it from a native memory pool which is generally not released back to the operating system when freed.
If you free memory and then allocate it later, that memory can be used for a different purpose. Continuing to use the old address can lead to corruption.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With