What’s the difference between StackOverflowError and OutOfMemoryError and how to avoid them in application?
What’s the difference between StackOverflowError and OutOfMemoryError and how to avoid them in application?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Short answer:
OutOfMemoryErroris related to Heap.StackOverflowErroris related to stackLong answer:
When you start
JVMyou define how much RAM it can use for processing.JVMdivides this into certain memory locations for its processing purpose, two of those areStack&HeapIf you have large objects (or) referenced objects in memory, then you will see
OutofMemoryError. If you have strong references to objects, then GC can’t clean the memory space allocated for that object. When JVM tries to allocate memory for new object and not enough space available it throwsOutofMemoryErrorbecause it can’t allocate the required amount of memory.How to avoid: Make sure un-necessary objects are available for GC
All your local variables and methods calls related data will be on the stack. For every method call, one stack frame will be created and local as well as method call related data will be placed inside the stack frame. Once method execution is completed, the stack frame will be removed. ONE WAY to reproduce this is, have an infinite loop for method call, you will see
stackoverflowerror, because stack frame will be populated with method data for every call but it won’t be freed (removed).How to avoid: Make sure method calls are ending (not in an infinite loop)