StackOverflowError at java.util.stream.Streams$ConcatSpliterator.estimateSize
原创 java_world 发表于:2023-11-26 01:46:57
  阅读 :125   收藏   编辑

异常信息

Exception in thread "main" java.lang.StackOverflowError
	at java.base/java.util.stream.Streams$ConcatSpliterator.characteristics(Streams.java:755)
	at java.base/java.util.stream.Streams$ConcatSpliterator.characteristics(Streams.java:755)
	at java.base/java.util.stream.Streams$ConcatSpliterator.characteristics(Streams.java:755)
	at java.base/java.util.stream.Streams$ConcatSpliterator.characteristics(Streams.java:755)
	at java.base/java.util.stream.Streams$ConcatSpliterator.characteristics(Streams.java:755)
	at java.base/java.util.stream.Streams$ConcatSpliterator.characteristics(Streams.java:755)

该异常通常是因为使用了Java8的Stream的concat方法,该方法在大量调用时会发生栈内存溢出

image.png

如运行下列方法

public static void main(String[] args) {
    int count = 200000;
    IntStream s[] = new IntStream[count];
    for (int i = 0; i < count; i++) {
      s[i] = Arrays.stream(new int[1]);
    }
    IntStream cs = s[0];
    for (int i = 1; i < count; i++) {
      cs = IntStream.concat(cs, s[i]);
    }
  }

解决办法

  1. 使用其他方法代替contact,应尽量避免使用
  2. 增加jvm的栈内存大小