banner
RustyNail

RustyNail

coder. 【blog】https://rustynail.me 【nostr】wss://ts.relays.world/ wss://relays.world/nostr

Java memory block memory overflow

Find a way to make the various partitions of Jvm OOM.

Heap Memory#

Heap memory overflow mainly occurs when objects are continuously created but cannot be garbage collected (reachability analysis, there is a reachable path between GC Root and objects), which will cause overflow.

Parameters: -Xmx20m -Xms20m -XX:+HeapDumpOnOutOfMemoryError

byte[] a = new byte[21 * 1024 * 1024];

Adding HeapDumpOnOutOfMemoryError can dump logs for subsequent analysis of the cause of OOM.

Stack Memory Overflow#

By continuously creating local variables in the virtual machine stack, the local variable table in the stack can be overloaded.

(I didn't succeed in OOM here, I don't know if it's because of Jvm or something else)

Parameters: -Xss1m -XX:+HeapDumpOnOutOfMemoryError

public void StackOOM() {
        while (true) {
            Thread thread = new Thread(this::job);
            thread.start();
        }
    }

    private void job() {
        while (true) {
        }

    }

Method Area Overflow#

The method area is used to store class information, so to overflow the method area, simply generate a large number of classes dynamically. A simple way to generate classes is to use Cglib. Therefore,

Projects that use Cglib may encounter method area overflow exceptions, such as Spring's Aop. If there are a large number of enhanced classes, many classes will be generated, and if the size of the method area is not enough, an exception will occur.

If using -XX:PermSize=1M -XX:MaxPermSize=1M, make sure the JVM version is lower than 8, because Java 1.8 removed the permanent generation and placed class information in the Meta Space.

Control Meta space with -XX:MetaspaceSize and -XX:MaxMetaspaceSize

Parameters: -XX=10m -XX=10m -Xmx20m -Xms10m

while (true){
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(TestMain.class);
    enhancer.setUseCache(false);
    enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> methodProxy.invokeSuper(o, objects));
    enhancer.create();
}

Exception in thread "main" java.lang.OutOfMemoryError: Metaspace

Direct Memory Overflow#

Direct memory overflow usually occurs in places where Nio appears, such as Netty. You can simulate direct memory overflow by directly requesting system memory using the unsafe method.

Parameters: -XX=10M -XX:+HeapDumpOnOutOfMemoryError

Field field = Unsafe.class.getDeclaredFields()[0];
    field.setAccessible(true);
    Unsafe unsafe = (Unsafe) field.get(null);
    while (true) {
        unsafe.allocateMemory(1 * 1024 * 1024);
}

Exception in thread "main" java.lang.OutOfMemoryError
at sun.misc.Unsafe.allocateMemory(Native Method)

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.