Skip to content

Instantly share code, notes, and snippets.

@orirawlings
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orirawlings/89b939dcd8023c108c8e to your computer and use it in GitHub Desktop.
Save orirawlings/89b939dcd8023c108c8e to your computer and use it in GitHub Desktop.
Java program which runs out of memory 10 times and then shuts down gracefully
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class OOMerHeap {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(10);
final ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new Runnable() {
@Override
public void run() {
latch.countDown();
if (latch.getCount() > 0) {
executor.submit(this);
}
System.out.println("About to run out of heap space...");
List<Object[]> list = new ArrayList<Object[]>();
while (true) {
list.add(new Object[99999]);
}
}
});
try {
latch.await();
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
System.out.println("Shutting down...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment