← 中文资源

简体中文版本

Java IllegalStateException: 常见触发场景

诊断 Java 的 IllegalStateException:迭代器误用、流重复使用与框架生命周期违规,并找出真正被破坏的状态不变式。

阅读英文原文

症状

即便参数合法,操作仍抛出 IllegalStateException。消息可能直接点明误用,例如 stream has already been operated upon or closed。

诊断

阅读被破坏的前置条件并检查对象状态:

Iterator<String> it = list.iterator();
while (it.hasNext()) {     // never call next() without hasNext()
    System.out.println(it.next());
}

Stream<String> s = list.stream();
s.forEach(System.out::println);
s.filter(x -> true);       // IllegalStateException: stream already consumed

修复

遵守生命周期,并为每次管道新建 Stream:

list.stream().filter(x -> x != null).forEach(System.out::println);

在使用组件前完成初始化,避免在关闭之后再操作。

验证

在测试中覆盖边界情况(空迭代器、重复消费的流);它们均无 IllegalStateException,说明对象只在合法状态下被使用。