What’s my ressources future when I get java.lang.OutOfMemoryError ?

A finally block are always called, even if the function returns in either the try block or the catch block.
But if my application shutdowns quickly (when I get java.lang.OutOfMemoryError, for example), can I trust in my finally block ?

Try a single test as follows :

public class HeapSpaceTest {
        public static void main(String[] argv) {
                List<String> l = new ArrayList<String>();
                try {
                        while (true) {
                                l.add("bim");
                        }
                } finally {
                        System.err.println("finally");
                }
        }
}

And you get :

[kaz@akina test]$ java HeapSpaceTest
finally
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.util.Arrays.copyOf(Arrays.java:2760)
	at java.util.Arrays.copyOf(Arrays.java:2734)
	at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
	at java.util.ArrayList.add(ArrayList.java:351)
	at HeapSpaceTest.main(HeapSpaceTest.java:9)

Yeah thanks very much finally, I trust in you !

Advertisements

2 thoughts on “What’s my ressources future when I get java.lang.OutOfMemoryError ?

  1. You should change the System.out.println part to System.err.println so the stacktrace and your message is syncronised. your problem is probably just a matter of buffering..

  2. You’re right, and now I’ve change out to err stream. But it’s not the problem here, and there are no differences between the both outputs.
    Keep in mind that even if OutOfMemoryError is thrown inside try block, finally will be proceed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s