问题描述
我到处找,找不到可靠的答案.根据文档,Java 抛出 java.lang.StackOverflowError 错误以下情况:
I've looked everywhere and can't find a solid answer. According to the documentation, Java throws a java.lang.StackOverflowError error under the following circumstance:
由于应用程序递归太深而发生堆栈溢出时引发.
Thrown when a stack overflow occurs because an application recurses too deeply.
但这提出了两个问题:
- 除了递归之外,没有其他方法可以发生堆栈溢出吗?
- StackOverflowError 发生在 JVM 实际溢出堆栈之前还是之后?
详细说明第二个问题:
当 Java 抛出 StackOverflowError 时,您可以安全地假设堆栈没有写入堆吗?如果你在一个抛出堆栈溢出的函数的 try/catch 中缩小堆栈或堆的大小,你能继续工作吗?这在任何地方都有记录吗?
When Java throws the StackOverflowError, can you safely assume that the stack did not write into the heap? If you shrink the size of the stack or heap in a try/catch on a function that throws a stack overflow, can you continue working? Is this documented anywhere?
我不想要的答案:
- 由于递归错误而发生 StackOverflow.
- 当堆遇到堆栈时会发生 StackOverflow.
推荐答案
看来你在想一个 stackoverflow 错误 就像本机程序中的缓冲区溢出异常,当存在写入尚未分配给缓冲区的内存的风险时,可能会损坏其他一些内存位置.根本不是这样的.
It seems you're thinking that a stackoverflow error is like a buffer overflow exception in native programs, when there is a risk of writing into memory that had not been allocated for the buffer, and thus to corrupt some other memory locations. It's not the case at all.
JVM 为每个线程的每个堆栈分配了给定的内存,如果尝试调用方法碰巧填满了该内存,则 JVM 会抛出错误.就像您尝试在长度为 N 的数组的索引 N 处写入一样.不会发生内存损坏.堆栈不能写入堆.
JVM has a given memory allocated for each stack of each thread, and if an attempt to call a method happens to fill this memory, JVM throws an error. Just like it would do if you were trying to write at index N of an array of length N. No memory corruption can happen. The stack can not write into the heap.
StackOverflowError 之于堆栈就像 OutOfMemoryError 之于堆:它只是表示没有更多可用内存.
A StackOverflowError is to the stack what an OutOfMemoryError is to the heap: it simply signals that there is no more memory available.
StackOverflowError:Java 虚拟机实现已用完线程的堆栈空间,这通常是因为线程正在执行无限数量的递归调用,因为正在执行的程序中出现错误.
StackOverflowError: The Java Virtual Machine implementation has run out of stack space for a thread, typically because the thread is doing an unbounded number of recursive invocations as a result of a fault in the executing program.
这篇关于究竟是什么导致堆栈溢出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!