开发中遇到的异常有哪些?
解答:java虚拟机规范允许java栈的大小是动态的或者是固定不变的。
1、如果采用固定大小的java虚拟机栈,那每个线程java的虚拟机栈容量可以在线程创建的时候独立选定。如果线程请求分配的栈容量超过java虚拟机栈允许的最大容量,java会抛出一个stackoverflowError异常。
2、如果java虚拟机可以动态扩展,并且尝试扩展的时候无法申请到足够的内存,或者在创建的线程时没有足够的内存去创建对应的虚拟机栈,那么将会抛出一个OutOfMemoryError异常。
查找java se官方文档.对于虚拟机栈默认大小设置如下:
-Xss size
Sets the thread stack size (in bytes). Append the letter k or K to indicate KB, m or M to indicate MB, and g or G to indicate GB. The default value depends on the platform:
Linux/x64 (64-bit): 1024 KB
macOS (64-bit): 1024 KB
Oracle Solaris/x64 (64-bit): 1024 KB
Windows: The default value depends on virtual memory
接下来利用一个例子来演示一下手动设置虚拟机栈的大小:
/**
* @author jw.z
* 演示StackOverflowError异常
* @date 2021/6/2 9:03 下午
* 默认大小:count:10822
*/
public class StackError {
public static int count = 1;
public static void main(String[] args) {
System.out.println(count);
count++;
main(args);
}
}
//执行结果
1
...
10822
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:691)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.j
设置栈大小
/**
* @author jw.z
* 演示StackOverflowError异常
* @date 2021/6/2 9:03 下午
* 默认大小:count:10822
* 设置栈大小:-Xss256k count:1872
*/
public class StackError {
public static int count = 1;
public static void main(String[] args) {
System.out.println(count);
count++;
main(args);
}
}
//执行结果
1
...
1872
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.UTF_8.updatePositions(UTF_8.java:77)
可以看出,当设置栈的容量变小时,打印的数量也变少了,一旦java线程请求分配的栈容量超过java虚拟机栈允许的最大容量,就会抛出StackOverfolError。