Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java write to / read from off heap memory that was freed?

Tags:

java

unsafe

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?

like image 889
Lubor Avatar asked Oct 19 '18 03:10

Lubor


People also ask

Is heap memory permanent?

Heap-memory is accessible or exists as long as the whole application(or java program) runs.

What is off-heap memory in Java?

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.

What is stored in off-heap memory?

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.

What happens when JVM runs out of memory?

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.


1 Answers

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.

like image 184
Peter Lawrey Avatar answered Oct 30 '22 17:10

Peter Lawrey