Is there a way for a thread to close if an exception occurs when any element of the constructed thread chain is called?
For example, the code:
Stream.of(new Object())
.filter(e -> {
if (true) throw new IllegalStateException();
return true;
})
.onClose(() -> System.out.println("OnClose"))
.collect(Collectors.toList());
will produce the following result:
Exception in thread "main" java.lang.IllegalStateException
at my.className.lambda$main$2(LdapRealm.java:114)
at my.className$$Lambda$1/1607521710.test(Unknown Source)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
at java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:419)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at my.className.main(LdapRealm.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Note that the message “OnClose” was not printed because onClose () was not called. Is there a good solution for this problem if I want this thread to be used by third-party code, and I'm not sure if this code will facilitate the try/catch+ function Autocloseable?
source
share