1

In Java, is it possible to accurately find the point at which java.lang.OutOfMemoryError occurred?

I am looking to better understand exactly how much memory did my application took a claim to before failing

4

1 回答 1

2

you could catch the OutOfMemoryError and ask the runtime as shown below.

try {
    //...
} catch (OutOfMemoryError er) {
    // this will tell you how much you have used
    long heapSize = Runtime.getRuntime().totalMemory();
    System.err.println("memory used "+heapSize);
}

(an OutOfMemoryError should occur when the heap runs out of memory)

if you have no idea where in your code it will fail, you could try register a shutdown hook and output the heapSize there.

于 2012-04-28T16:54:26.443 回答