StackOverflowError和OutOfMemoryError之间的区别是什么 [英] What's the difference between StackOverflowError and OutOfMemoryError

查看:1171
本文介绍了StackOverflowError和OutOfMemoryError之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

StackOverflowError和OutOfMemoryError之间有什么区别以及如何在应用程序中避免它们?

What's the difference between StackOverflowError and OutOfMemoryError and how to avoid them in application?

推荐答案

简答:


  • OutOfMemoryError 与堆有关。

  • StackOverflowError 与堆栈相关

  • OutOfMemoryError is related to Heap.
  • StackOverflowError is related to stack

答案很长:

当您启动 JVM 时,您可以定义多少RAM可以用于处理。 JVM 将其划分到某些内存位置以进行处理,其中两个是 Stack &

When you start JVM you define how much RAM it can use for processing. JVM divides this into certain memory locations for its processing purpose, two of those are Stack & Heap

如果内存中有大对象(或)引用的对象,那么你会看到的OutOfMemoryError 。如果您对对象有强引用,则GC无法清除为该对象分配的内存空间。当JVM尝试为新对象分配内存而没有足够的可用空间时,它会抛出 OutofMemoryError ,因为它无法分配所需的内存量。

If 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 throws OutofMemoryError because it can't allocate the required amount of memory.

如何避免:确保GC可以使用不必要的对象

How to avoid: Make sure un-necessary objects are available for GC

所有本地变量和方法调用相关数据将在堆栈中。对于每个方法调用,将创建一个堆栈帧,并将本地以及与方法调用相关的数据放置在堆栈帧内。方法执行完成后,将删除堆栈帧。重现这一点的方法是,有一个无限循环的方法调用,你会看到 stackoverflow 错误,因为堆栈帧将填充每个调用的方法数据,但它赢了'被释放(删除)。

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 stackoverflow error, 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)

这篇关于StackOverflowError和OutOfMemoryError之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆