BAEL-7063: OOM example (#15730)

This commit is contained in:
Eugene Kovko 2024-01-25 19:56:45 +01:00 committed by GitHub
parent 450e82b2ca
commit 6c53d9f828
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,52 @@
package com.baeldung.oom;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@Disabled
class OomCrashUnitTest {
public static final Runnable MEMORY_LEAK = () -> {
List<byte[]> list = new ArrayList<>();
while (true) {
list.add(tenMegabytes());
}
};
@Test
void givenMemoryLeakCode_whenRunInsideThread_thenMainAppDoestFail() throws InterruptedException {
Thread memoryLeakThread = new Thread(MEMORY_LEAK);
memoryLeakThread.start();
memoryLeakThread.join();
}
@Test
void givenMemoryLeakCode_whenRunSeveralTimesInsideThread_thenMainAppDoestFail() throws InterruptedException {
for (int i = 0; i < 5; i++) {
Thread memoryLeakThread = new Thread(MEMORY_LEAK);
memoryLeakThread.start();
memoryLeakThread.join();
}
}
@Test
void givenBadExample_whenUseItInProductionCode_thenQuestionedByEmployerAndProbablyFired()
throws InterruptedException {
Thread npeThread = new Thread(() -> {
String nullString = null;
try {
nullString.isEmpty();
} catch (NullPointerException e) {
throw new OutOfMemoryError(e.getMessage());
}
});
npeThread.start();
npeThread.join();
}
private static byte[] tenMegabytes() {
return new byte[1024 * 1014 * 10];
}
}