How do you test code that uses OutOfMemoryError?

This article discusses methods for testing code that may lead to an OutOfMemoryError in Java, including strategies to gracefully handle memory exhaustion and simulate high memory usage conditions.

OutOfMemoryError, Java, Memory Management, Exception Handling, Unit Testing

// Example code to simulate OutOfMemoryError in Java public class MemoryTest { public static void main(String[] args) { try { // Attempt to use a large amount of memory List memoryHog = new ArrayList<>(); while (true) { memoryHog.add(new byte[1_000_000]); // Allocate 1MB } } catch (OutOfMemoryError e) { System.out.println("Caught an OutOfMemoryError: " + e.getMessage()); } } }

OutOfMemoryError Java Memory Management Exception Handling Unit Testing